我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用platform.system()。
def testHelpMessageForSQLitePlugin(self): """test the --help option for SQLite""" helper = end_to_end_test_helper.EndToEndTestHelper('not needed', 'not needed') if platform.system() in ['Linux']: message_help = ( 'Usage: main.py sqlite [OPTIONS]\r\n\r\n' 'Options:\r\n ' '--path TEXT The path to plaso\r\n ' '--name TEXT The plugin name\r\n ' '--testfile TEXT The testfile path\r\n ' '--sql / --no-sql The output example flag for the SQL Query for the ' 'plugin.\r\n ' '--help Show this message and exit.') command = 'python {0} sqlite --help'.format(helper.MAIN_PATH) child = pexpect.spawn(command) child.expect_exact(message_help) else: raise NotImplementedError("test only implemented for linux platform")
def mss(*args, **kwargs): ''' Factory returning a proper MSS class instance. It detects the plateform we are running on and choose the most adapted mss_class to take screenshots. It then proxies its arguments to the class for instantiation. ''' operating_system = system().lower() if operating_system == 'darwin': from .darwin import MSS elif operating_system == 'linux': from .linux import MSS elif operating_system == 'windows': from .windows import MSS else: err = 'System "{0}" not implemented.'.format(operating_system) raise ScreenshotError(err) return MSS(*args, **kwargs)
def get_path(filename = None): if platform.system() == "Windows": separator = "\\" else: separator = "/" try: filename = filename.split('/') #For in code expressions except: pass _path = Path.cwd() if filename != None: for i in filename: if i != None: _path = PurePath(_path, i) _path = str(_path) return _path
def default_environment(): if hasattr(sys, 'implementation'): iver = format_full_version(sys.implementation.version) implementation_name = sys.implementation.name else: iver = '0' implementation_name = '' return { "implementation_name": implementation_name, "implementation_version": iver, "os_name": os.name, "platform_machine": platform.machine(), "platform_release": platform.release(), "platform_system": platform.system(), "platform_version": platform.version(), "python_full_version": platform.python_version(), "platform_python_implementation": platform.python_implementation(), "python_version": platform.python_version()[:3], "sys_platform": sys.platform, }
def __addRightClickMenu(self, widget): widget.bind("<FocusIn>", self.__checkCopyAndPaste, add="+") widget.bind("<FocusOut>", self.__checkCopyAndPaste, add="+") if widget.var is None: # TEXT: widget.bind('<KeyRelease>', self.__checkCopyAndPaste) widget.bind('<<Paste>>', self.__checkCopyAndPaste) else: widget.var.trace( "w", lambda name, index, mode, e=None, w=widget: self.__checkCopyAndPaste( e, w)) # ENTRY/OPTION if self.platform in [self.WINDOWS, self.LINUX]: widget.bind('<Button-3>', self.__rightClick) else: widget.bind('<Button-2>', self.__rightClick)
def __buildTextArea(self, title, frame, scrollable=False): self.__verifyItem(self.n_textAreas, title, True) if scrollable: text = AjScrolledText(frame) else: text = AjText(frame) text.config(font=self.taFont, width=20, height=10, undo=True) if self.platform in [self.MAC, self.LINUX]: text.config(highlightbackground=self.__getContainerBg()) text.bind("<Tab>", self.__focusNextWindow) text.bind("<Shift-Tab>", self.__focusLastWindow) # add a right click menu text.var = None self.__addRightClickMenu(text) self.n_textAreas[title] = text self.logTextArea(title) return text # add external dnd support
def get_firefox_db(db_file): '''Return the full path of firefox sqlite databases, platform independent''' success = False plat_dict = {"Windows 7" : r"C:\Users\%s\AppData\Roaming\Mozilla\Firefox\Profiles" % os.getlogin(), "Windows XP" : r"C:\Documents and Settings\%s\Application Data\Mozilla\Firefox\Profiles" % os.getlogin(), "Linux" : r"/home/%s/.mozilla/firefox/" % os.getlogin(), "Darwin" : r"/Users/%s/Library/Application Support/Firefox/Profiles" % os.getlogin()} if platform.system() == "Windows": string = plat_dict[platform.system() + " " + platform.release()] else: string = plat_dict[platform.system()] for item in os.listdir(string): if os.path.isdir(os.path.join(string, item)) and "default" in item: if os.path.isfile(os.path.join(string, item, db_file)): success = True return os.path.join(string, item, db_file) if not success: sys.exit("Couldn't find the database file in the default location! Try providing a different location using the -b option...")
def capture( self, event_name, event_properties=None ): event_properties = event_properties or dict() user_properties = dict( path=self.instance.game.server_path, server_name=self.instance.game.server_name, language=self.instance.game.server_language, login=self.instance.game.server_player_login, title=self.instance.game.dedicated_title, dedicated_build=self.instance.game.dedicated_build, dedicated_version=self.instance.game.dedicated_version, ) await self.execute(dict( user_id=self.instance.game.server_player_login, event_type=event_name, event_properties=event_properties, user_properties=user_properties, app_version=version, platform=platform.platform(), os_name=platform.system(), os_version=platform.version(), language=self.instance.game.server_language ))
def disable_journal(): """ Disables logging in CICS (except for system logs) """ number_journals = 0; all_journals = 0; em.move_to(1,2) req_set_jour = CEMT+" S JOURNAL ALL DIS" em.safe_send(format_request(req_set_jour)) em.send_enter() data = em.screen_get() for d in data: if "Jou(" in d and "NORMAL" in d and "Dis" in d and "DFHLOG" not in d: number_journals +=1; all_journals += 1; elif "Jou(" in d and "NORMAL" not in d and "Ena" in d and "DFHLOG" not in d: pos= d.find("Jou(") + len("Jou(") whine("Journal "+d[pos:pos+8]+" could not be disabled",'err') all_journals += 1; if number_journals > 0: whine(str(number_journals)+" of "+str(all_journals) +" journals were disabled",'good') else: whine("Only DFHLOG is defined, cannot disable this system log",'err')
def testHelpMessage(self): """test the universal --help Option""" helper = end_to_end_test_helper.EndToEndTestHelper('not needed', 'not needed') if platform.system() in ['Linux']: message_help = ('Usage: main.py [OPTIONS] COMMAND [ARGS]...\r\n\r\n' 'Options:\r\n' ' --help Show this message and exit.\r\n\r\n' 'Commands:\r\n' ' sqlite') command = 'python {0} --help'.format(helper.MAIN_PATH) child = pexpect.spawn(command) child.expect_exact(message_help) else: raise NotImplementedError("test only implemented for linux platform")
def launch(self, cfg, path, flags): logging.debug("Determine the OS and Architecture this application is currently running on") hostOS = platform.system().lower() logging.debug("hostOS: " + str(hostOS)) is_64bits = sys.maxsize > 2 ** 32 if is_64bits: hostArchitecture = 'x64' else: hostArchitecture = 'ia32' logging.debug("hostArchitecture: " + str(hostArchitecture)) if(self.validateConfig(cfg, hostOS, hostArchitecture)): fnull = open(os.devnull, 'w') if os.environ.get("WPW_HOME") is not None: cmd = [os.environ["WPW_HOME"] + '/bin/rpc-agent-' + platform.system().lower() + '-' + self.detectHostArchitecture()] else: cmd = [path + '/wpwithinpy/iot-core-component/bin/rpc-agent-' + platform.system().lower() + '-' + self.detectHostArchitecture()] cmd.extend(flags) proc = subprocess.Popen(cmd, stdin=None, stdout=fnull, stderr=subprocess.STDOUT) return proc else: logging.debug("Invalid OS/Architecture combination detected")
def __start_driver(self, aport, bpport): """ ??logcat?appium???? :return: """ if platform.system() == 'Windows': # ?win10??appium?bug,?????? import subprocess subprocess.Popen("appium -p %s -bp %s -U %s" % (aport, bpport, self.device), shell=True) else: appium = U.cmd("appium -p %s -bp %s -U %s" % (aport, bpport, self.device)) # ??appium while True: appium_line = appium.stdout.readline().strip() U.Logging.debug(appium_line) U.sleep(1) if 'listener started' in appium_line or 'Error: listen' in appium_line: break
def get_pid(self, package_name): """ ????pid args: - packageName -: ???? usage: getPid("com.android.settings") """ if system is "Windows": pidinfo = self.shell( "ps | findstr %s$" % package_name).stdout.read() else: pidinfo = self.shell( "ps | %s -w %s" % (find_util, package_name)).stdout.read() if pidinfo == '': return "the process doesn't exist." pattern = re.compile(r"\d+") result = pidinfo.split(" ") result.remove(result[0]) return pattern.findall(" ".join(result))[0]
def from_object(self, obj): """Update the values from the given object. Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: from yourapplication import default_config app.config.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an object holding the configuration """ for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key)
def get_filename(self): if Config.library_file: return Config.library_file import platform import ctypes.util name = platform.system() if name == 'Windows': filename = 'libclang.dll' else: # Does the right thing on Linux and MacOS X filename = ctypes.util.find_library ('clang') # On Ubuntu, find_library fails and returns None # this will break loading below so replace with libclang.so if filename is None: return 'libclang.so' if Config.library_path: filename = Config.library_path + '/' + filename return filename
def validate_result_ordering(self, results): """ This method will validate that the timestamps returned from the result are in order. This indicates that the results were returned in the order they were submitted for execution :param results: """ last_time_added = 0 for success, result in results: self.assertTrue(success) current_time_added = list(result)[0] #Windows clock granularity makes this equal most of the times if "Windows" in platform.system(): self.assertLessEqual(last_time_added, current_time_added) else: self.assertLess(last_time_added, current_time_added) last_time_added = current_time_added
def not_init_assertions(self): self.assert_(not pygame.display.get_init(), "display shouldn't be initialized" ) if 'pygame.mixer' in sys.modules: self.assert_(not pygame.mixer.get_init(), "mixer shouldn't be initialized" ) if 'pygame.font' in sys.modules: self.assert_(not pygame.font.get_init(), "init shouldn't be initialized" ) ## !!! TODO : Remove when scrap works for OS X import platform if platform.system().startswith('Darwin'): return try: self.assertRaises(pygame.error, pygame.scrap.get) except NotImplementedError: # Scrap is optional. pass # pygame.cdrom # pygame.joystick
def check_remote(url): # TODO need a better solution o = urlparse.urlparse(url) host = o.netloc while "@" in host: host = host[host.find("@")+1:] while ":" in host: host = host[:host.find(":")] cmd = list() cmd.append("ping") if platform.system().lower().startswith("win"): cmd.append("-n") cmd.append("1") cmd.append("-w") cmd.append("1000") else: cmd.append("-c1") cmd.append("-t1") cmd.append(host) p = Popen(" ".join(cmd), stdout=PIPE, stderr=PIPE, shell=True) out, err = p.communicate() return len(err) == 0
def get_environment_variables(self, plan): """Get all environment variables depends on selected plan""" envs = list() if isinstance(plan, dict): if 'environment' in plan: if 'include' in plan['environment']: envs.extend(ProjectUtils.get_list_value(plan['environment']['include'])) if 'docker-compose-dir' in plan: envs.extend(FileUtils.get_filtered_sorted_alter_from_base_dir(base_dir=self.repo_dir, actual_dir=self.working_directory, target_directories=ProjectUtils. get_list_value( plan['docker-compose-dir']), filter_ends='.env')) env_dict = self.get_environment_dict(envs=envs) env_copy = os.environ.copy() for key in env_dict.keys(): env_copy[key] = env_dict[key] """Add host system to environment""" env_copy["HOST_SYSTEM"] = platform.system() return env_copy
def get_script_base(self): command_array = list() command_array.append("docker") command_array.append("run") """Add host system to environment""" command_array.append("-e") command_array.append("HOST_SYSTEM="+platform.system()) command_array.append("-u") command_array.append("1000") command_array.append("-v") command_array.append(str(self.working_directory) + ":/usr/local") command_array.append("-w") command_array.append("/usr/local") command_array.append("alpine:latest") command_array.append("/bin/sh") command_array.append("-c") return command_array
def build_user_agent(): """Build a Mozilla/5.0 compatible User-Agent string""" global USER_AGENT if USER_AGENT: return USER_AGENT ua_tuple = ( 'Mozilla/5.0', '(%s; U; %s; en-us)' % (platform.system(), platform.architecture()[0]), 'Python/%s' % platform.python_version(), '(KHTML, like Gecko)', 'speedtest-cli/%s' % __version__ ) USER_AGENT = ' '.join(ua_tuple) printer(USER_AGENT, debug=True) return USER_AGENT
def __init__(self, name): self._host = CONF.api_listen self._port = CONF.api_listen_port if platform.system() == "Windows": self._workers = 1 else: self._workers = ( CONF.api_workers or processutils.get_worker_count()) self._loader = wsgi.Loader(CONF) self._app = self._loader.load_app(name) self._server = wsgi.Server(CONF, name, self._app, host=self._host, port=self._port)
def tls_insecure_set(self, value): """Configure verification of the server hostname in the server certificate. If value is set to true, it is impossible to guarantee that the host you are connecting to is not impersonating your server. This can be useful in initial server testing, but makes it possible for a malicious third party to impersonate your server through DNS spoofing, for example. Do not use this function in a real system. Setting value to true means there is no point using encryption. Must be called before connect().""" if HAVE_SSL is False: raise ValueError('This platform has no SSL/TLS.') self._tls_insecure = value
def do_beep(reason): """do beep with PC speacker. Work only on Linux and requrement motherboard speaker""" if not need_beep: return 0 if (datetime.datetime.now().time().hour < 9 or datetime.datetime.now().time().hour > 22) and silent_mode_at_night: debug_messages("Not beep, because too late") return 0 if platform.system() == "Linux" or platform.system() == "FreeBSD": if reason == "coockie_exept": call(["beep", "-l 2000", "-f 1900", "-r 3"]) elif reason == "critical": call(["beep", "-l 1000", "-r 10", "-f 1900"]) elif reason == "won": os.system("./win.sh") elif reason == "bad_words": call(["beep", "-l 300", "-r 30", "-f 1900"])
def _start_from_profile_path(self, path): self._firefox_env["XRE_PROFILE_PATH"] = path if platform.system().lower() == 'linux': self._modify_link_library_path() command = [self._start_cmd, "-silent"] if self.command_line is not None: for cli in self.command_line: command.append(cli) # The following exists upstream and is known to create hanging # firefoxes, leading to zombies. # subprocess.Popen(command, stdout=self._log_file, # stderr=subprocess.STDOUT, # env=self._firefox_env).communicate() command[1] = '-foreground' self.process = subprocess.Popen( command, stdout=self._log_file, stderr=subprocess.STDOUT, env=self._firefox_env)
def helpAbout(self, copyrightDate, about, version=1.0): """ This is a helper method for easily adding a generic help messageBox to self Creates a about MessageBox :param copyrightDate : string , the copyright date for the tool :param about : string, the about information """ __version__ = version QtWidgets.QMessageBox.about(self, "About" + self.objectName(), "<b>'About {0}</b> v {1}Copyright © 2007,{2}.All rights reserved.\ <p>Python {3} - Qt {4} - PyQt {5} on {6}".format(copyrightDate, about, __version__, platform.python_version(), QtCore.QT_VERSION_STR, QtCore.PYQT_VERSION_STR, platform.system()))
def __initMenu(self): # create a menu bar - only shows if populated if not self.hasMenu: # self.topLevel.option_add('*tearOff', FALSE) self.hasMenu = True self.menuBar = Menu(self.topLevel) if self.platform == self.MAC: appmenu = Menu(self.menuBar, name='apple') self.menuBar.add_cascade(menu=appmenu) self.n_menus["MAC_APP"] = appmenu elif self.platform == self.WINDOWS: # sysMenu must be added last, otherwise other menus vanish sysMenu = Menu(self.menuBar, name='system', tearoff=False) self.n_menus["WIN_SYS"] = sysMenu # add a parent menu, for menu items
def _setup_environment(environ): # Cygwin requires some special voodoo to set the environment variables # properly so that Oracle will see them. if platform.system().upper().startswith('CYGWIN'): try: import ctypes except ImportError as e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Error loading ctypes: %s; " "the Oracle backend requires ctypes to " "operate correctly under Cygwin." % e) kernel32 = ctypes.CDLL('kernel32') for name, value in environ: kernel32.SetEnvironmentVariableA(name, value) else: os.environ.update(environ)
def host_config(self): """ Ensure the host configuration file exists """ if platform.system() == 'Darwin': default_file_dir = os.path.join(os.path.expanduser("~"), "vent_files") else: default_file_dir = "/opt/vent_files" status = self.ensure_dir(default_file_dir) config = Template(template=self.cfg_file) sections = {'main': {'files': default_file_dir}, 'network-mapping': {}, 'nvidia-docker-plugin': {'port': '3476'}} for s in sections: if sections[s]: for option in sections[s]: config.add_option(s, option, sections[s][option]) else: config.add_section(s) config.write_config() return status
def start_server(project): if not tern_command: return None if time.time() - project.last_failed < 30: return None env = None if platform.system() == "Darwin": env = os.environ.copy() env["PATH"] += ":/usr/local/bin" proc = subprocess.Popen(tern_command + tern_arguments, cwd=project.dir, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=windows) output = "" while True: line = proc.stdout.readline().decode("utf-8") if not line: sublime.error_message("Failed to start server" + (output and ":\n" + output)) project.last_failed = time.time() return None match = re.match("Listening on port (\\d+)", line) if match: project.proc = proc return int(match.group(1)) else: output += line
def communicate(input, coro=None): if platform.system() == 'Windows': # asyncfile.Popen must be used instead of subprocess.Popen pipe = asyncoro.asyncfile.Popen([r'\cygwin64\bin\sha1sum.exe'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) else: pipe = subprocess.Popen(['sha1sum'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) # convert pipe to asynchronous version async_pipe = asyncoro.asyncfile.AsyncPipe(pipe) # 'communicate' takes either the data or file descriptor with data # (if file is too large to read in full) as input input = open(input) stdout, stderr = yield async_pipe.communicate(input) print('communicate sha1sum: %s' % stdout)
def custom_feeder(input, coro=None): def write_proc(fin, pipe, coro=None): while True: data = yield os.read(fin.fileno(), 8*1024) if not data: break n = yield pipe.write(data, full=True) assert n == len(data) fin.close() pipe.stdin.close() def read_proc(pipe, coro=None): # output from sha1sum is small, so read until EOF data = yield pipe.stdout.read() pipe.stdout.close() raise StopIteration(data) if platform.system() == 'Windows': # asyncfile.Popen must be used instead of subprocess.Popen pipe = asyncoro.asyncfile.Popen([r'\cygwin64\bin\sha1sum.exe'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) else: pipe = subprocess.Popen(['sha1sum'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) async_pipe = asyncoro.asyncfile.AsyncPipe(pipe) reader = asyncoro.Coro(read_proc, async_pipe) writer = asyncoro.Coro(write_proc, open(input), async_pipe) stdout = yield reader.finish() print(' feeder sha1sum: %s' % stdout) # asyncoro.logger.setLevel(asyncoro.Logger.DEBUG) # simpler version using 'communicate'