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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
Source File: desktop.py From godot-mono-builds with MIT License | 5 votes |
def is_cross_compiling(target_platform: str) -> bool: return (sys.platform == 'darwin' and target_platform != 'osx') or \ (sys.platform in ['linux', 'linux2', 'cygwin'] and target_platform != 'linux')
Example #20
Source File: android.py From godot-mono-builds with MIT License | 5 votes |
def get_api_version_or_min(opts: AndroidOpts, target: str) -> str: min_versions = { 'arm64-v8a': '21', 'x86_64': '21' } if target in min_versions and int(opts.android_api_version) < int(min_versions[target]): print('WARNING: %s is less than minimum platform for %s; using %s' % (opts.android_api_version, target, min_versions[target])) return min_versions[target] return opts.android_api_version
Example #21
Source File: android.py From godot-mono-builds with MIT License | 5 votes |
def get_android_libclang_path(opts): if sys.platform == 'darwin': return '%s/toolchains/llvm/prebuilt/darwin-x86_64/lib64/libclang.dylib' % opts.android_ndk_root elif sys.platform in ['linux', 'linux2']: loc = '%s/toolchains/llvm/prebuilt/linux-x86_64/lib64/libclang.so.9svn' % opts.android_ndk_root if os.path.isfile(loc): return loc return '%s/toolchains/llvm/prebuilt/linux-x86_64/lib64/libclang.so.8svn' % opts.android_ndk_root assert False
Example #22
Source File: versioneer.py From aospy with Apache License 2.0 | 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 #23
Source File: versioneer.py From xrft 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 #24
Source File: plugins.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def set_handler(self, signal, listener=None): """Subscribe a handler for the given signal (number or name). If the optional 'listener' argument is provided, it will be subscribed as a listener for the given signal's channel. If the given signal name or number is not available on the current platform, ValueError is raised. """ if isinstance(signal, text_or_bytes): signum = getattr(_signal, signal, None) if signum is None: raise ValueError('No such signal: %r' % signal) signame = signal else: try: signame = self.signals[signal] except KeyError: raise ValueError('No such signal: %r' % signal) signum = signal prev = _signal.signal(signum, self._handle_signal) self._previous_handlers[signum] = prev if listener is not None: self.bus.log('Listening for %s.' % signame) self.bus.subscribe(signame, listener)
Example #25
Source File: wspbus.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _do_execv(self): """Re-execute the current process. This must be called from the main thread, because certain platforms (OS X) don't allow execv to be called in a child thread very well. """ try: args = self._get_true_argv() except NotImplementedError: """It's probably win32 or GAE""" args = [sys.executable] + self._get_interpreter_argv() + sys.argv self.log('Re-spawning %s' % ' '.join(args)) self._extend_pythonpath(os.environ) if sys.platform[:4] == 'java': from _systemrestart import SystemRestart raise SystemRestart else: if sys.platform == 'win32': args = ['"%s"' % arg for arg in args] os.chdir(_startup_cwd) if self.max_cloexec_files: self._set_cloexec() os.execv(sys.executable, args)
Example #26
Source File: btrecon.py From btrecon with MIT License | 5 votes |
def color(text, color_code): if sys.platform == "win32" and os.getenv("TERM") != "xterm": return text return '\x1b[%dm%s\x1b[0m' % (color_code, text)
Example #27
Source File: bd_server.py From sump2 with GNU General Public License v3.0 | 5 votes |
def rd( self, bytes_to_read ): bytes_to_read = bytes_to_read * 4;# Only using 8 of 16bit of FT600, ASCII channel = 0; rx_pipe = 0x82 + channel; if sys.platform == 'linux2': rx_pipe -= 0x82; output = self.D3XX.readPipeEx( rx_pipe, bytes_to_read ); xferd = output['bytesTransferred'] if sys.version_info.major == 3: buff_read = output['bytes'].decode('latin1'); else: buff_read = output['bytes']; while (xferd != bytes_to_read ): status = self.D3XX.getLastError() if (status != 0): print("ERROR READ %d (%s)" % (status,self.D3XX.getStrError(status))); if sys.platform == 'linux2': return self.D3XX.flushPipe(pipe); else: return self.D3XX.abortPipe(pipe); output = self.D3XX.readPipeEx( rx_pipe, bytes_to_read - xferd ); status = self.D3XX.getLastError() xferd += output['bytesTransferred'] if sys.version_info.major == 3: buff_read += output['bytes'].decode('latin1') else: buff_read += output['bytes'] if ( self.debug ): print("FT600_RD:" + buff_read[0::2] ); return buff_read[0::2];# Return every other ch as using 8 of 16 FT600 bits
Example #28
Source File: _Beep.py From zmirror with MIT License | 5 votes |
def beep(): import sys # A stock AMIGA 1200 using Python 1.4 or greater. # This assumes that the sound is enabled in the PREFS: drawer. # AND/OR the screen flash is enabled also. if sys.platform == 'amiga': print('\a\v') # MS Windows (TM), from Windows ME upwards. Used in Command # Prompt mode for best effect. # The *.WAV file can be anything of your choice. # CHORD.WAV was the default. # SNDREC32.EXE no longer exists in WIndows Vista, and higher? if sys.platform == 'win32': from winsound import Beep Beep(770, 1000) # os.system('SNDREC32.EXE "C:\WINDOWS\MEDIA\CHORD.WAV" /EMBEDDING /PLAY /CLOSE') # print(chr(7)) # A generic error beep for all Linux platforms. # There is a simple way to change the frequency, and the amplitude. # This also works in a Linux terminal running a Python interpreter! if 'linux' in sys.platform: audio = open('/dev/audio', 'wb') count = 0 while count < 250: beep = chr(63) + chr(63) + chr(63) + chr(63) audio.write(beep) beep = chr(0) + chr(0) + chr(0) + chr(0) audio.write(beep) count = count + 1 audio.close() # Add here for other OSs. # Add here any peculiarities. # if sys.platform=='some-platform': # Do some sound error beep.
Example #29
Source File: versioneer.py From NiBetaSeries 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 #30
Source File: test_project.py From python-template with Apache License 2.0 | 5 votes |
def load_yaml(filename): """Return object in yaml file.""" with open(filename) as myfile: content = myfile.read() if "win" in sys.platform: content = content.replace("\\", "/") return yaml.safe_load(content)