Python sys.platform() Examples
The following are 30
code examples of sys.platform().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sys
, or try the search function
.
Example #1
Source File: plugins.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 7 votes |
def __init__(self, bus): self.bus = bus # Set default handlers self.handlers = {'SIGTERM': self.bus.exit, 'SIGHUP': self.handle_SIGHUP, 'SIGUSR1': self.bus.graceful, } if sys.platform[:4] == 'java': del self.handlers['SIGUSR1'] self.handlers['SIGUSR2'] = self.bus.graceful self.bus.log('SIGUSR1 cannot be set on the JVM platform. ' 'Using SIGUSR2 instead.') self.handlers['SIGINT'] = self._jython_SIGINT_handler self._previous_handlers = {} # used to determine is the process is a daemon in `self._is_daemonized` self._original_pid = os.getpid()
Example #2
Source File: utils.py From calmjs with GNU General Public License v2.0 | 6 votes |
def rmtree(path): try: rmtree_(path) except (IOError, OSError): # As it turns out nested node_modules directories are a bad # idea, especially on Windows. It turns out this situation # is rather common, so we need a way to deal with this. As # it turns out a workaround exists around this legacy win32 # issue through this proprietary prefix: path_ = '\\\\?\\' + path if sys.platform == 'win32' else path # and try again try: rmtree_(path_) except (IOError, OSError): pass # Don't blow the remaining teardown up if it fails anyway. if exists(path): warnings.warn("rmtree failed to remove %r" % path)
Example #3
Source File: platform.py From jawfish with MIT License | 6 votes |
def _syscmd_uname(option,default=''): """ Interface to the system's uname command. """ if sys.platform in ('dos','win32','win16','os2'): # XXX Others too ? return default try: f = os.popen('uname %s 2> %s' % (option, DEV_NULL)) except (AttributeError,os.error): return default output = f.read().strip() rc = f.close() if not output or rc: return default else: return output
Example #4
Source File: support.py From jawfish with MIT License | 6 votes |
def _requires_unix_version(sysname, min_version): """Decorator raising SkipTest if the OS is `sysname` and the version is less than `min_version`. For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if the FreeBSD version is less than 7.2. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): if platform.system() == sysname: version_txt = platform.release().split('-', 1)[0] try: version = tuple(map(int, version_txt.split('.'))) except ValueError: pass else: if version < min_version: min_version_txt = '.'.join(map(str, min_version)) raise unittest.SkipTest( "%s version %s or higher required, not %s" % (sysname, min_version_txt, version_txt)) return wrapper return decorator
Example #5
Source File: bd_server.py From sump2 with GNU General Public License v3.0 | 6 votes |
def wr( self, str ): if ( self.debug ): print("FT600_WR:" + str ); str = "~".join( str );# only using 8bits of 16bit FT600, so pad with ~ bytes_to_write = len( str );# str is now "~1~2~3 .. ~e~f" - Twice as long channel = 0; result = False; timeout = 5; tx_pipe = 0x02 + channel; if sys.platform == 'linux2': tx_pipe -= 0x02; if ( sys.version_info.major == 3 ): str = str.encode('latin1'); xferd = 0 while ( xferd != bytes_to_write ): # write data to specified pipe xferd += self.D3XX.writePipe(tx_pipe,str,bytes_to_write-xferd); return;
Example #6
Source File: atari_game.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def ale_load_from_rom(rom_path, display_screen): rng = get_numpy_rng() try: from ale_python_interface import ALEInterface except ImportError as e: raise ImportError('Unable to import the python package of Arcade Learning Environment. ' \ 'ALE may not have been installed correctly. Refer to ' \ '`https://github.com/mgbellemare/Arcade-Learning-Environment` for some' \ 'installation guidance') ale = ALEInterface() ale.setInt(b'random_seed', rng.randint(1000)) if display_screen: import sys if sys.platform == 'darwin': import pygame pygame.init() ale.setBool(b'sound', False) # Sound doesn't work on OSX ale.setBool(b'display_screen', True) else: ale.setBool(b'display_screen', False) ale.setFloat(b'repeat_action_probability', 0) ale.loadROM(str.encode(rom_path)) return ale
Example #7
Source File: tarfile.py From jawfish with MIT License | 6 votes |
def makelink(self, tarinfo, targetpath): """Make a (symbolic) link called targetpath. If it cannot be created (platform limitation), we try to make a copy of the referenced file instead of a link. """ try: # For systems that support symbolic and hard links. if tarinfo.issym(): os.symlink(tarinfo.linkname, targetpath) else: # See extract(). if os.path.exists(tarinfo._link_target): os.link(tarinfo._link_target, targetpath) else: self._extract_member(self._find_link_target(tarinfo), targetpath) except symlink_exception: try: self._extract_member(self._find_link_target(tarinfo), targetpath) except KeyError: raise ExtractError("unable to resolve link inside archive")
Example #8
Source File: main.py From friendly-telegram with GNU Affero General Public License v3.0 | 6 votes |
def parse_arguments(): """Parse the arguments""" parser = argparse.ArgumentParser() parser.add_argument("--setup", "-s", action="store_true") parser.add_argument("--phone", "-p", action="append") parser.add_argument("--token", "-t", action="append", dest="tokens") parser.add_argument("--heroku", action="store_true") parser.add_argument("--local-db", dest="local", action="store_true") parser.add_argument("--web-only", dest="web_only", action="store_true") parser.add_argument("--no-web", dest="web", action="store_false") parser.add_argument("--heroku-web-internal", dest="heroku_web_internal", action="store_true", help="This is for internal use only. If you use it, things will go wrong.") arguments = parser.parse_args() logging.debug(arguments) if sys.platform == "win32": # Subprocess support; not needed in 3.8 but not harmful asyncio.set_event_loop(asyncio.ProactorEventLoop()) return arguments
Example #9
Source File: test_asymmetric.py From oscrypto with MIT License | 6 votes |
def test_dsa_2048_sha1_sign(self): def do_run(): original_data = b'This is data to sign' private = asymmetric.load_private_key(os.path.join(fixtures_dir, 'keys/test-dsa-2048.key')) public = asymmetric.load_public_key(os.path.join(fixtures_dir, 'keys/test-dsa-2048.crt')) signature = asymmetric.dsa_sign(private, original_data, 'sha1') self.assertIsInstance(signature, byte_cls) asymmetric.dsa_verify(public, signature, original_data, 'sha1') if sys.platform == 'win32': with self.assertRaises(errors.AsymmetricKeyError): do_run() else: do_run()
Example #10
Source File: cd_tools.py From Andromeda with MIT License | 6 votes |
def cd_sys_type(): """ :return: 平台类型 0 win, 1 mac 2 Linux 3 其他 """ """ a = sys.platform if a == 'win32' or a == 'win64': return 0 elif a == 'darwin': return 1 else: return 2 """ a = platform.system() if a == 'Windows': return 0 elif a == 'Darwin': return 1 elif a == 'Linux': return 2 else: return 3
Example #11
Source File: run_atari.py From lirpg with MIT License | 6 votes |
def train(env_id, num_timesteps, seed, policy): ncpu = multiprocessing.cpu_count() if sys.platform == 'darwin': ncpu //= 2 config = tf.ConfigProto(allow_soft_placement=True, intra_op_parallelism_threads=ncpu, inter_op_parallelism_threads=ncpu) config.gpu_options.allow_growth = True #pylint: disable=E1101 tf.Session(config=config).__enter__() env = VecFrameStack(make_atari_env(env_id, 8, seed), 4) policy = {'cnn' : CnnPolicy, 'lstm' : LstmPolicy, 'lnlstm' : LnLstmPolicy}[policy] ppo2.learn(policy=policy, env=env, nsteps=128, nminibatches=4, lam=0.95, gamma=0.99, noptepochs=4, log_interval=1, ent_coef=.01, lr=lambda f : f * 2.5e-4, cliprange=lambda f : f * 0.1, total_timesteps=int(num_timesteps * 1.1))
Example #12
Source File: epr.py From epr with MIT License | 6 votes |
def find_media_viewer(): global VWR VWR_LIST = [ "feh", "gio", "sxiv", "gnome-open", "gvfs-open", "xdg-open", "kde-open", "firefox" ] if sys.platform == "win32": VWR = ["start"] elif sys.platform == "darwin": VWR = ["open"] else: for i in VWR_LIST: if shutil.which(i) is not None: VWR = [i] break if VWR[0] in {"gio"}: VWR.append("open")
Example #13
Source File: utils.py From calmjs with GNU General Public License v2.0 | 6 votes |
def finalize_env(env): """ Produce a platform specific env for passing into subprocess.Popen family of external process calling methods, and the supplied env will be updated on top of it. Returns a new env. """ keys = _PLATFORM_ENV_KEYS.get(sys.platform, []) if 'PATH' not in keys: # this MUST be available due to Node.js (and others really) # needing something to look for binary locations when it shells # out to other binaries. keys.append('PATH') results = { key: os.environ.get(key, '') for key in keys } results.update(env) return results
Example #14
Source File: setup.py From contextualbandits with BSD 2-Clause "Simplified" License | 6 votes |
def build_extensions(self): compiler = self.compiler.compiler_type if compiler == 'msvc': # visual studio for e in self.extensions: e.extra_compile_args += ['/O2', '/openmp'] else: for e in self.extensions: e.extra_compile_args += ['-O3', '-march=native', '-fopenmp'] e.extra_link_args += ['-fopenmp'] if e.language == "c++": e.extra_compile_args += ['-std=c++11'] ### Remove this code if you have a mac with gcc or clang + openmp if platform[:3] == "dar": for e in self.extensions: e.extra_compile_args = [arg for arg in e.extra_compile_args if arg != '-fopenmp'] e.extra_link_args = [arg for arg in e.extra_link_args if arg != '-fopenmp'] build_ext.build_extensions(self)
Example #15
Source File: utils.py From WSL-Distribution-Switcher with MIT License | 6 votes |
def hide_cursor(): """ Turns the cursor off in the terminal. """ global is_conemu if not sys.platform == 'win32': sys.stdout.write('\033[?25l') is_conemu = False else: ci = ConsoleCursorInfo() handle = ctypes.windll.kernel32.GetStdHandle(-11) ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci)) ci.visible = False ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci)) is_conemu = os.environ.get('ConEmuANSI') == 'ON' # some characters are forbidden in NTFS, but are not in ext4. the most popular of these characters # seems to be the colon character. LXSS solves this issue by escaping the character on NTFS. # while this seems like a dumb implementation, it will be called a lot of times inside the # decompression loop, so it has to be fast: http://stackoverflow.com/a/27086669/156626
Example #16
Source File: test_utils.py From calmjs with GNU General Public License v2.0 | 6 votes |
def test_found_win32(self): sys.platform = 'win32' tempdir = os.environ['PATH'] = mkdtemp(self) os.environ['PATHEXT'] = pathsep.join(('.com', '.exe', '.bat')) f = join(tempdir, 'binary.exe') with open(f, 'w'): pass os.chmod(f, 0o777) self.assertEqual(which('binary'), f) self.assertEqual(which('binary.exe'), f) self.assertEqual(which(f), f) self.assertIsNone(which('binary.com')) os.environ['PATH'] = '' self.assertEqual(which('binary', path=tempdir), f) self.assertEqual(which('binary.exe', path=tempdir), f) self.assertEqual(which(f, path=tempdir), f) self.assertIsNone(which('binary.com', path=tempdir))
Example #17
Source File: test_utils.py From calmjs with GNU General Public License v2.0 | 6 votes |
def test_finalize_env_win32(self): sys.platform = 'win32' # when os.environ is empty or missing the required keys, the # values will be empty strings. os.environ = {} self.assertEqual(finalize_env({}), { 'APPDATA': '', 'PATH': '', 'PATHEXT': '', 'SYSTEMROOT': ''}) # should be identical with the keys copied os.environ['APPDATA'] = 'C:\\Users\\Guest\\AppData\\Roaming' os.environ['PATH'] = 'C:\\Windows' os.environ['PATHEXT'] = pathsep.join(('.com', '.exe', '.bat')) os.environ['SYSTEMROOT'] = 'C:\\Windows' self.assertEqual(finalize_env({}), os.environ) # This test is done with conjunction with finalize_env to mimic how # this is typically used within the rest of the library.
Example #18
Source File: subprocess.py From jawfish with MIT License | 5 votes |
def _find_w9xpopen(self): """Find and return absolut path to w9xpopen.exe""" w9xpopen = os.path.join( os.path.dirname(_winapi.GetModuleFileName(0)), "w9xpopen.exe") if not os.path.exists(w9xpopen): # Eeek - file-not-found - possibly an embedding # situation - see if we can locate it in sys.exec_prefix w9xpopen = os.path.join(os.path.dirname(sys.base_exec_prefix), "w9xpopen.exe") if not os.path.exists(w9xpopen): raise RuntimeError("Cannot locate w9xpopen.exe, which is " "needed for Popen to work with your " "shell or platform.") return w9xpopen
Example #19
Source File: versioneer.py From btle-sniffer with MIT License | 5 votes |
def do_vcs_install(manifest_in, versionfile_source, ipy): """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py for export-subst keyword substitution. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [manifest_in, versionfile_source] if ipy: files.append(ipy) try: me = __file__ if me.endswith(".pyc") or me.endswith(".pyo"): me = os.path.splitext(me)[0] + ".py" versioneer_file = os.path.relpath(me) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: f = open(".gitattributes", "r") for line in f.readlines(): if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True f.close() except EnvironmentError: pass if not present: f = open(".gitattributes", "a+") f.write("%s export-subst\n" % versionfile_source) f.close() files.append(".gitattributes") run_command(GITS, ["add", "--"] + files)
Example #20
Source File: zipfile.py From jawfish with MIT License | 5 votes |
def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)): self.orig_filename = filename # Original file name in archive # Terminate the file name at the first null byte. Null bytes in file # names are used as tricks by viruses in archives. null_byte = filename.find(chr(0)) if null_byte >= 0: filename = filename[0:null_byte] # This is used to ensure paths in generated ZIP files always use # forward slashes as the directory separator, as required by the # ZIP format specification. if os.sep != "/" and os.sep in filename: filename = filename.replace(os.sep, "/") self.filename = filename # Normalized file name self.date_time = date_time # year, month, day, hour, min, sec if date_time[0] < 1980: raise ValueError('ZIP does not support timestamps before 1980') # Standard values: self.compress_type = ZIP_STORED # Type of compression for the file self.comment = b"" # Comment for each file self.extra = b"" # ZIP extra data if sys.platform == 'win32': self.create_system = 0 # System which created ZIP archive else: # Assume everything else is unix-y self.create_system = 3 # System which created ZIP archive self.create_version = DEFAULT_VERSION # Version which created ZIP archive self.extract_version = DEFAULT_VERSION # Version needed to extract archive self.reserved = 0 # Must be zero self.flag_bits = 0 # ZIP flag bits self.volume = 0 # Volume number of file header self.internal_attr = 0 # Internal attributes self.external_attr = 0 # External file attributes # Other attributes are set by class ZipFile: # header_offset Byte offset to the file header # CRC CRC-32 of the uncompressed file # compress_size Size of the compressed file # file_size Size of the uncompressed file
Example #21
Source File: __init__.py From oscrypto with MIT License | 5 votes |
def backend(): """ :return: A unicode string of the backend being used: "openssl", "mac", "win", "winlegacy" """ if _module_values['backend'] is not None: return _module_values['backend'] with _backend_lock: if _module_values['backend'] is not None: return _module_values['backend'] if sys.platform == 'win32': # Windows XP was major version 5, Vista was 6 if sys.getwindowsversion()[0] < 6: _module_values['backend'] = 'winlegacy' else: _module_values['backend'] = 'win' elif sys.platform == 'darwin': _module_values['backend'] = 'mac' else: _module_values['backend'] = 'openssl' return _module_values['backend']
Example #22
Source File: zipfile.py From jawfish with MIT License | 5 votes |
def _extract_member(self, member, targetpath, pwd): """Extract the ZipInfo object 'member' to a physical file on the path targetpath. """ # build the destination pathname, replacing # forward slashes to platform specific separators. arcname = member.filename.replace('/', os.path.sep) if os.path.altsep: arcname = arcname.replace(os.path.altsep, os.path.sep) # interpret absolute pathname as relative, remove drive letter or # UNC path, redundant separators, "." and ".." components. arcname = os.path.splitdrive(arcname)[1] invalid_path_parts = ('', os.path.curdir, os.path.pardir) arcname = os.path.sep.join(x for x in arcname.split(os.path.sep) if x not in invalid_path_parts) if os.path.sep == '\\': # filter illegal characters on Windows arcname = self._sanitize_windows_name(arcname, os.path.sep) targetpath = os.path.join(targetpath, arcname) targetpath = os.path.normpath(targetpath) # Create all upper directories if necessary. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): os.makedirs(upperdirs) if member.filename[-1] == '/': if not os.path.isdir(targetpath): os.mkdir(targetpath) return targetpath with self.open(member, pwd=pwd) as source, \ open(targetpath, "wb") as target: shutil.copyfileobj(source, target) return targetpath
Example #23
Source File: regrtest.py From jawfish with MIT License | 5 votes |
def printlist(x, width=70, indent=4): """Print the elements of iterable x to stdout. Optional arg width (default 70) is the maximum line length. Optional arg indent (default 4) is the number of blanks with which to begin each line. """ from textwrap import fill blanks = ' ' * indent # Print the sorted list: 'x' may be a '--random' list or a set() print(fill(' '.join(str(elt) for elt in sorted(x)), width, initial_indent=blanks, subsequent_indent=blanks)) # Map sys.platform to a string containing the basenames of tests # expected to be skipped on that platform. # # Special cases: # test_pep277 # The _ExpectedSkips constructor adds this to the set of expected # skips if not os.path.supports_unicode_filenames. # test_timeout # Controlled by test_timeout.skip_expected. Requires the network # resource and a socket module. # # Tests that are expected to be skipped everywhere except on one platform # are also handled separately.
Example #24
Source File: regrtest.py From jawfish with MIT License | 5 votes |
def getexpected(self): """Return set of test names we expect to skip on current platform. self.isvalid() must be true. """ assert self.isvalid() return self.expected
Example #25
Source File: utils.py From WSL-Distribution-Switcher with MIT License | 5 votes |
def show_cursor(): """ Turns the cursor back on in the terminal. """ if not sys.platform == 'win32': sys.stdout.write('\033[?25h') else: ci = ConsoleCursorInfo() handle = ctypes.windll.kernel32.GetStdHandle(-11) ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci)) ci.visible = True ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
Example #26
Source File: cli.py From quart with MIT License | 5 votes |
def shell_command(info: ScriptInfo) -> None: app = info.load_app() context = {} context.update(app.make_shell_context()) banner = f"Python {sys.version} on {sys.platform} running {app.import_name}" code.interact(banner=banner, local=context)
Example #27
Source File: os_utils.py From godot-mono-builds with MIT License | 5 votes |
def try_find_libclang(toolchain_path: str = '', llvm_config=''): import sys from subprocess import check_output hint_paths = [] if toolchain_path: libclang = os.path.join(toolchain_path, 'usr', 'lib', 'libclang.dylib') if os.path.isfile(libclang): print('Found libclang at: \'%s\'' % libclang) return libclang if not llvm_config: llvm_config = find_executable('llvm-config') if not llvm_config: print('WARNING: llvm-config not found') return '' elif not os.path.isfile(llvm_config): raise RuntimeError('Specified llvm-config file not found: \'%s\'' % llvm_config) llvm_libdir = check_output([llvm_config, '--libdir']).strip().decode('utf-8') if llvm_libdir: libsuffix = '.dylib' if sys.platform == 'darwin' else '.so' hints = ['libclang', 'clang'] libclang = next((p for p in [os.path.join(llvm_libdir, h + libsuffix) for h in hints] if os.path.isfile(p)), '') if libclang: print('Found libclang at: \'%s\'' % libclang) return libclang return ''
Example #28
Source File: support.py From jawfish with MIT License | 5 votes |
def requires_mac_ver(*min_version): """Decorator raising SkipTest if the OS is Mac OS X and the OS X version if less than min_version. For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version is lesser than 10.5. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): if sys.platform == 'darwin': version_txt = platform.mac_ver()[0] try: version = tuple(map(int, version_txt.split('.'))) except ValueError: pass else: if version < min_version: min_version_txt = '.'.join(map(str, min_version)) raise unittest.SkipTest( "Mac OS X %s or higher required, not %s" % (min_version_txt, version_txt)) return func(*args, **kw) wrapper.min_version = min_version return wrapper return decorator
Example #29
Source File: support.py From jawfish with MIT License | 5 votes |
def check_impl_detail(**guards): """This function returns True or False depending on the host platform. Examples: if check_impl_detail(): # only on CPython (default) if check_impl_detail(jython=True): # only on Jython if check_impl_detail(cpython=False): # everywhere except on CPython """ guards, default = _parse_guards(guards) return guards.get(platform.python_implementation().lower(), default)
Example #30
Source File: versioneer.py From matchpy with MIT License | 5 votes |
def do_vcs_install(manifest_in, versionfile_source, ipy): """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py for export-subst keyword substitution. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [manifest_in, versionfile_source] if ipy: files.append(ipy) try: me = __file__ if me.endswith(".pyc") or me.endswith(".pyo"): me = os.path.splitext(me)[0] + ".py" versioneer_file = os.path.relpath(me) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: f = open(".gitattributes", "r") for line in f.readlines(): if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True f.close() except EnvironmentError: pass if not present: f = open(".gitattributes", "a+") f.write("%s export-subst\n" % versionfile_source) f.close() files.append(".gitattributes") run_command(GITS, ["add", "--"] + files)