Python os.environ() Examples

The following are code examples for showing how to use os.environ(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: fs_image   Author: facebookincubator   File: test_subvolume_garbage_collector.py    MIT License 9 votes vote down vote up
def setUp(self):
        # Mock out `sudo btrfs subvolume delete` for the garbage-collector,
        # so that the test doesn't require us to set up & clean up btrfs
        # volumes.  Everything else is easily tested in a tempdir.
        self._old_path = os.environ.pop('PATH', None)
        self.addCleanup(self._restore_path)
        fake_sudo_path = os.path.join(
            os.path.dirname(os.path.dirname(__file__)), 'fake_sudo/'
        )
        os.environ['PATH'] = f'{fake_sudo_path}:{self._old_path}'

        # Ensure the sudo override worked, so we don't mysteriously fail later.
        fake_sudo_file = os.path.join(fake_sudo_path, 'sudo')
        self.assertTrue(os.path.exists(fake_sudo_file), fake_sudo_file)
        self.assertEqual(
            b'MAGIC_SENTINEL',
            subprocess.check_output(['sudo', 'MAGIC_SENTINEL']),
        ) 
Example 2
Project: godot-mono-builds   Author: godotengine   File: os_utils.py    MIT License 7 votes vote down vote up
def find_executable(name) -> str:
    is_windows = os.name == 'nt'
    windows_exts = ENV_PATH_SEP.split(os.environ['PATHEXT']) if is_windows else None
    path_dirs = ENV_PATH_SEP.split(os.environ['PATH'])

    search_dirs = path_dirs + [os.getcwd()] # cwd is last in the list

    for dir in search_dirs:
        path = os.path.join(dir, name)

        if is_windows:
            for extension in windows_exts:
                path_with_ext = path + extension

                if os.path.isfile(path_with_ext) and os.access(path_with_ext, os.X_OK):
                    return path_with_ext
        else:
            if os.path.isfile(path) and os.access(path, os.X_OK):
                return path

    return '' 
Example 3
Project: leapp-repository   Author: oamg   File: library.py    Apache License 2.0 6 votes vote down vote up
def _get_cmd_output(cmd, delim, expected_len):
    ''' Verify if command exists and return output '''
    if not any(os.access(os.path.join(path, cmd[0]), os.X_OK) for path in os.environ['PATH'].split(os.pathsep)):
        api.current_logger().warning("'%s': command not found" % cmd[0])
        raise StopIteration

    try:
        # FIXME: Will keep call to subprocess until our stdlib supports "env" parameter
        # when there is any fd except 0,1,2 open, lvm closes the fd and prints a warning.
        # In our case /dev/urandom has other fd opened, probably for caching purposes.
        output = subprocess.check_output(cmd, env={'LVM_SUPPRESS_FD_WARNINGS': '1', 'PATH': os.environ['PATH']})

    except subprocess.CalledProcessError as e:
        api.current_logger().debug("Command '%s' return non-zero exit status: %s" % (" ".join(cmd), e.returncode))
        raise StopIteration

    for entry in output.split('\n'):
        entry = entry.strip()
        if not entry:
            continue

        data = entry.split(delim)
        data.extend([''] * (expected_len - len(data)))

        yield data 
Example 4
Project: godot-mono-builds   Author: godotengine   File: runtime.py    MIT License 6 votes vote down vote up
def run_configure(env: dict, opts: RuntimeOpts, product: str, target: str):
    build_dir = path_join(opts.configure_dir, '%s-%s-%s' % (product, target, opts.configuration))
    mkdir_p(build_dir)

    def str_dict_val(val):
        if isinstance(val, list):
            return ' '.join(val) # Don't need to surround with quotes
        return val

    ac_vars = env['_runtime_%s-%s_AC_VARS' % (product, target)]
    configure_env_args = env['_runtime_%s-%s_CONFIGURE_ENVIRONMENT' % (product, target)]
    configure_env_args = [('%s=%s' % (key, str_dict_val(value))) for (key, value) in configure_env_args.items()]
    configure_flags = env['_runtime_%s-%s_CONFIGURE_FLAGS' % (product, target)]

    configure = path_join(opts.mono_source_root, 'configure')
    configure_args = ac_vars + configure_env_args + configure_flags

    configure_env = os.environ.copy()
    target_extra_path = env.get('_%s-%s_PATH' % (product, target), '')
    if target_extra_path:
        configure_env['PATH'] += ':' + target_extra_path

    run_command(configure, args=configure_args, cwd=build_dir, env=configure_env, name='configure') 
Example 5
Project: pyblish-win   Author: pyblish   File: _osx_support.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _find_executable(executable, path=None):
    """Tries to find 'executable' in the directories listed in 'path'.

    A string listing directories separated by 'os.pathsep'; defaults to
    os.environ['PATH'].  Returns the complete filename or None if not found.
    """
    if path is None:
        path = os.environ['PATH']

    paths = path.split(os.pathsep)
    base, ext = os.path.splitext(executable)

    if (sys.platform == 'win32' or os.name == 'os2') and (ext != '.exe'):
        executable = executable + '.exe'

    if not os.path.isfile(executable):
        for p in paths:
            f = os.path.join(p, executable)
            if os.path.isfile(f):
                # the file exists, we have a shot at spawn working
                return f
        return None
    else:
        return executable 
Example 6
Project: pyblish-win   Author: pyblish   File: _osx_support.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _check_for_unavailable_sdk(_config_vars):
    """Remove references to any SDKs not available"""
    # If we're on OSX 10.5 or later and the user tries to
    # compile an extension using an SDK that is not present
    # on the current machine it is better to not use an SDK
    # than to fail.  This is particularly important with
    # the standalone Command Line Tools alternative to a
    # full-blown Xcode install since the CLT packages do not
    # provide SDKs.  If the SDK is not present, it is assumed
    # that the header files and dev libs have been installed
    # to /usr and /System/Library by either a standalone CLT
    # package or the CLT component within Xcode.
    cflags = _config_vars.get('CFLAGS', '')
    m = re.search(r'-isysroot\s+(\S+)', cflags)
    if m is not None:
        sdk = m.group(1)
        if not os.path.exists(sdk):
            for cv in _UNIVERSAL_CONFIG_VARS:
                # Do not alter a config var explicitly overriden by env var
                if cv in _config_vars and cv not in os.environ:
                    flags = _config_vars[cv]
                    flags = re.sub(r'-isysroot\s+\S+(?:\s|$)', ' ', flags)
                    _save_modified_value(_config_vars, cv, flags)

    return _config_vars 
Example 7
Project: pyblish-win   Author: pyblish   File: mailcap.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def listmailcapfiles():
    """Return a list of all mailcap files found on the system."""
    # XXX Actually, this is Unix-specific
    if 'MAILCAPS' in os.environ:
        str = os.environ['MAILCAPS']
        mailcaps = str.split(':')
    else:
        if 'HOME' in os.environ:
            home = os.environ['HOME']
        else:
            # Don't bother with getpwuid()
            home = '.' # Last resort
        mailcaps = [home + '/.mailcap', '/etc/mailcap',
                '/usr/etc/mailcap', '/usr/local/etc/mailcap']
    return mailcaps


# Part 2: the parser. 
Example 8
Project: pyblish-win   Author: pyblish   File: sysconfig.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _getuserbase():
    env_base = os.environ.get("PYTHONUSERBASE", None)
    def joinuser(*args):
        return os.path.expanduser(os.path.join(*args))

    # what about 'os2emx', 'riscos' ?
    if os.name == "nt":
        base = os.environ.get("APPDATA") or "~"
        return env_base if env_base else joinuser(base, "Python")

    if sys.platform == "darwin":
        framework = get_config_var("PYTHONFRAMEWORK")
        if framework:
            return env_base if env_base else \
                               joinuser("~", "Library", framework, "%d.%d"
                                            % (sys.version_info[:2]))

    return env_base if env_base else joinuser("~", ".local") 
Example 9
Project: pyblish-win   Author: pyblish   File: cgi.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def read_multi(self, environ, keep_blank_values, strict_parsing):
        """Internal: read a part that is itself multipart."""
        ib = self.innerboundary
        if not valid_boundary(ib):
            raise ValueError, 'Invalid boundary in multipart form: %r' % (ib,)
        self.list = []
        if self.qs_on_post:
            for key, value in urlparse.parse_qsl(self.qs_on_post,
                                self.keep_blank_values, self.strict_parsing):
                self.list.append(MiniFieldStorage(key, value))
            FieldStorageClass = None

        klass = self.FieldStorageClass or self.__class__
        part = klass(self.fp, {}, ib,
                     environ, keep_blank_values, strict_parsing)
        # Throw first part away
        while not part.done:
            headers = rfc822.Message(self.fp)
            part = klass(self.fp, headers, ib,
                         environ, keep_blank_values, strict_parsing)
            self.list.append(part)
        self.skip_lines() 
Example 10
Project: pyblish-win   Author: pyblish   File: msvccompiler.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def find_exe(self, exe):
        """Return path to an MSVC executable program.

        Tries to find the program in several places: first, one of the
        MSVC program search paths from the registry; next, the directories
        in the PATH environment variable.  If any of those work, return an
        absolute path that is known to exist.  If none of them work, just
        return the original program name, 'exe'.
        """

        for p in self.__paths:
            fn = os.path.join(os.path.abspath(p), exe)
            if os.path.isfile(fn):
                return fn

        # didn't find it; try existing path
        for p in string.split(os.environ['Path'],';'):
            fn = os.path.join(os.path.abspath(p),exe)
            if os.path.isfile(fn):
                return fn

        return exe 
Example 11
Project: pyblish-win   Author: pyblish   File: util.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def check_environ ():
    """Ensure that 'os.environ' has all the environment variables we
    guarantee that users can use in config files, command-line options,
    etc.  Currently this includes:
      HOME - user's home directory (Unix only)
      PLAT - description of the current platform, including hardware
             and OS (see 'get_platform()')
    """
    global _environ_checked
    if _environ_checked:
        return

    if os.name == 'posix' and 'HOME' not in os.environ:
        import pwd
        os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]

    if 'PLAT' not in os.environ:
        os.environ['PLAT'] = get_platform()

    _environ_checked = 1 
Example 12
Project: pyblish-win   Author: pyblish   File: util.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def subst_vars (s, local_vars):
    """Perform shell/Perl-style variable substitution on 'string'.  Every
    occurrence of '$' followed by a name is considered a variable, and
    variable is substituted by the value found in the 'local_vars'
    dictionary, or in 'os.environ' if it's not in 'local_vars'.
    'os.environ' is first checked/augmented to guarantee that it contains
    certain values: see 'check_environ()'.  Raise ValueError for any
    variables not found in either 'local_vars' or 'os.environ'.
    """
    check_environ()
    def _subst (match, local_vars=local_vars):
        var_name = match.group(1)
        if var_name in local_vars:
            return str(local_vars[var_name])
        else:
            return os.environ[var_name]

    try:
        return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
    except KeyError, var:
        raise ValueError, "invalid variable '$%s'" % var

# subst_vars () 
Example 13
Project: pyblish-win   Author: pyblish   File: test_config.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def setUp(self):
        """Patches the environment."""
        super(PyPIRCCommandTestCase, self).setUp()
        self.tmp_dir = self.mkdtemp()
        os.environ['HOME'] = self.tmp_dir
        self.rc = os.path.join(self.tmp_dir, '.pypirc')
        self.dist = Distribution()

        class command(PyPIRCCommand):
            def __init__(self, dist):
                PyPIRCCommand.__init__(self, dist)
            def initialize_options(self):
                pass
            finalize_options = initialize_options

        self._cmd = command
        self.old_threshold = set_threshold(WARN) 
Example 14
Project: pyblish-win   Author: pyblish   File: spawn.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def find_executable(executable, path=None):
    """Tries to find 'executable' in the directories listed in 'path'.

    A string listing directories separated by 'os.pathsep'; defaults to
    os.environ['PATH'].  Returns the complete filename or None if not found.
    """
    if path is None:
        path = os.environ['PATH']
    paths = path.split(os.pathsep)
    base, ext = os.path.splitext(executable)

    if (sys.platform == 'win32' or os.name == 'os2') and (ext != '.exe'):
        executable = executable + '.exe'

    if not os.path.isfile(executable):
        for p in paths:
            f = os.path.join(p, executable)
            if os.path.isfile(f):
                # the file exists, we have a shot at spawn working
                return f
        return None
    else:
        return executable 
Example 15
Project: pyblish-win   Author: pyblish   File: msvc9compiler.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def find_exe(self, exe):
        """Return path to an MSVC executable program.

        Tries to find the program in several places: first, one of the
        MSVC program search paths from the registry; next, the directories
        in the PATH environment variable.  If any of those work, return an
        absolute path that is known to exist.  If none of them work, just
        return the original program name, 'exe'.
        """
        for p in self.__paths:
            fn = os.path.join(os.path.abspath(p), exe)
            if os.path.isfile(fn):
                return fn

        # didn't find it; try existing path
        for p in os.environ['Path'].split(';'):
            fn = os.path.join(os.path.abspath(p),exe)
            if os.path.isfile(fn):
                return fn

        return exe 
Example 16
Project: pyblish-win   Author: pyblish   File: test_loadtk.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testLoadTkFailure(self):
        old_display = None
        if sys.platform.startswith(('win', 'darwin', 'cygwin')):
            # no failure possible on windows?

            # XXX Maybe on tk older than 8.4.13 it would be possible,
            # see tkinter.h.
            return
        with test_support.EnvironmentVarGuard() as env:
            if 'DISPLAY' in os.environ:
                del env['DISPLAY']
                # on some platforms, deleting environment variables
                # doesn't actually carry through to the process level
                # because they don't support unsetenv
                # If that's the case, abort.
                display = os.popen('echo $DISPLAY').read().strip()
                if display:
                    return

            tcl = Tcl()
            self.assertRaises(TclError, tcl.winfo_geometry)
            self.assertRaises(TclError, tcl.loadtk) 
Example 17
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def run(self, application):
        """Invoke the application"""
        # Note to self: don't move the close()!  Asynchronous servers shouldn't
        # call close() from finish_response(), so if you close() anywhere but
        # the double-error branch here, you'll break asynchronous servers by
        # prematurely closing.  Async servers must return from 'run()' without
        # closing if there might still be output to iterate over.
        try:
            self.setup_environ()
            self.result = application(self.environ, self.start_response)
            self.finish_response()
        except:
            try:
                self.handle_error()
            except:
                # If we get an error handling an error, just give up already!
                self.close()
                raise   # ...and let the actual server figure it out. 
Example 18
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def setup_environ(self):
        """Set up the environment for one request"""

        env = self.environ = self.os_environ.copy()
        self.add_cgi_vars()

        env['wsgi.input']        = self.get_stdin()
        env['wsgi.errors']       = self.get_stderr()
        env['wsgi.version']      = self.wsgi_version
        env['wsgi.run_once']     = self.wsgi_run_once
        env['wsgi.url_scheme']   = self.get_scheme()
        env['wsgi.multithread']  = self.wsgi_multithread
        env['wsgi.multiprocess'] = self.wsgi_multiprocess

        if self.wsgi_file_wrapper is not None:
            env['wsgi.file_wrapper'] = self.wsgi_file_wrapper

        if self.origin_server and self.server_software:
            env.setdefault('SERVER_SOFTWARE',self.server_software) 
Example 19
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def error_output(self, environ, start_response):
        """WSGI mini-app to create error output

        By default, this just uses the 'error_status', 'error_headers',
        and 'error_body' attributes to generate an output page.  It can
        be overridden in a subclass to dynamically generate diagnostics,
        choose an appropriate message for the user's preferred language, etc.

        Note, however, that it's not recommended from a security perspective to
        spit out diagnostics to any old user; ideally, you should have to do
        something special to enable diagnostic output, which is why we don't
        include any here!
        """
        start_response(self.error_status,self.error_headers[:],sys.exc_info())
        return [self.error_body]


    # Pure abstract methods; *must* be overridden in subclasses 
Example 20
Project: pyblish-win   Author: pyblish   File: optparse.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self,
                 indent_increment,
                 max_help_position,
                 width,
                 short_first):
        self.parser = None
        self.indent_increment = indent_increment
        if width is None:
            try:
                width = int(os.environ['COLUMNS'])
            except (KeyError, ValueError):
                width = 80
            width -= 2
        self.width = width
        self.help_position = self.max_help_position = \
                min(max_help_position, max(width - 20, indent_increment * 2))
        self.current_indent = 0
        self.level = 0
        self.help_width = None          # computed later
        self.short_first = short_first
        self.default_tag = "%default"
        self.option_strings = {}
        self._short_opt_fmt = "%s %s"
        self._long_opt_fmt = "%s=%s" 
Example 21
Project: fs_image   Author: facebookincubator   File: test_unsanitized_env.py    MIT License 5 votes vote down vote up
def test_env(self):
        # Comes from Buck
        self.assertIn('BUCK_BUILD_ID', os.environ)
        # Comes from the test's `env`
        self.assertEqual('meow', os.environ['kitteh']) 
Example 22
Project: fs_image   Author: facebookincubator   File: test_image_python_unittest.py    MIT License 5 votes vote down vote up
def test_env(self):
        # Ensure that per-test `env` settings do reach the container.
        self.assertEqual('meow', os.environ.pop('kitteh'))
        # Ensure that the container's environment is sanitized.
        env_whitelist = {
            # Session basics
            'HOME',
            'LOGNAME',
            'NOTIFY_SOCKET',
            'PATH',
            'TERM',
            'USER',

            # Provided by the shell running the test
            'PWD',
            'SHLVL',

            # `nspawn --as-pid2` sets these 2, although they're quite silly.
            'container',
            'container_uuid',  # our nspawn runtime actually sets this to ''

            # These 2 are another `systemd` artifact, appearing when we pass
            # FDs into the container.
            'LISTEN_FDS',
            'LISTEN_PID',

            # PAR noise that doesn't start with `FB_PAR_` (filtered below)
            'PAR_LAUNCH_TIMESTAMP',
            'SCRIBE_LOG_USAGE',
            'LC_ALL',
            'LC_CTYPE',
        }
        for var in os.environ:
            if var.startswith('FB_PAR_'):  # Set for non-in-place build modes
                continue
            self.assertIn(var, env_whitelist)
        # If the whitelist proves unmaintainable, Buck guarantees that this
        # variable is set, and it is NOT explicitly passed into containers,
        # so it ought to be absent.  See also `test-unsanitized-env`.
        self.assertNotIn('BUCK_BUILD_ID', os.environ) 
Example 23
Project: fs_image   Author: facebookincubator   File: test_subvolume_garbage_collector.py    MIT License 5 votes vote down vote up
def _restore_path(self):
        os.environ['PATH'] = self._old_path 
Example 24
Project: fs_image   Author: facebookincubator   File: test_send_fds_and_run.py    MIT License 5 votes vote down vote up
def _run(argv):
    env = os.environ
    env.pop('SUDO_COMMAND', None)  # So we can assert whether `sudo` was used
    with send_fds_and_popen(
        parse_opts(argv),
        env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
    ) as proc:
        stdout, stderr = proc.communicate()
    return proc.returncode, stdout.decode(), stderr.decode() 
Example 25
Project: leapp-repository   Author: oamg   File: run_pytest.py    Apache License 2.0 5 votes vote down vote up
def test_libraries(libraries):
    for lib, name in libraries:
        os.environ['LEAPP_TESTED_LIBRARY'] = lib[0]
        cmd = pytest_cmd + [lib[0]]
        if args.report:
            cmd += ['--junit-xml={REPORT}'.format(REPORT=REPORT_DIR + name + '.xml')]
        logger.info(" Running pytest with: {PYTEST_CMD}".format(PYTEST_CMD=' '.join(cmd)))
        pytest_status.add(subprocess.call(cmd)) 
Example 26
Project: leapp-repository   Author: oamg   File: run_pytest.py    Apache License 2.0 5 votes vote down vote up
def test_actors(actors):
    for i, actor in enumerate(actors):
        # Run tests if actor has any.
        if not actor.tests:
            status = " Tests MISSING: {ACTOR} | class={CLASS}"
            status = status.format(ACTOR=actor.name, CLASS=actor.class_name)
            logger.critical(status)
        else:
            os.environ['LEAPP_TESTED_ACTOR'] = actor.full_path
            cmd = pytest_cmd + [actor.full_path]
            if args.report:
                cmd += ['--junit-xml={REPORT}'.format(REPORT=REPORT_DIR + actor.name + str(i) + '.xml')]
            logger.info(" Running pytest with: {PYTEST_CMD}".format(PYTEST_CMD=' '.join(cmd)))
            pytest_status.add(subprocess.call(cmd)) 
Example 27
Project: jumpserver-python-sdk   Author: jumpserver   File: test_auth.py    GNU General Public License v2.0 5 votes vote down vote up
def test_load_from_env(self):
        env_var = "XX_ACCESS_KEY"
        os.environ[env_var] = self.access_key_val
        access_key = AccessKey()
        access_key.load_from_env(env_var)
        self.assertEqual(access_key, self.access_key) 
Example 28
Project: jumpserver-python-sdk   Author: jumpserver   File: test_auth.py    GNU General Public License v2.0 5 votes vote down vote up
def test_load_from_conf_env(self):
        os.environ[self.key_env_var] = self.access_key_val
        app_access_key = deepcopy(self.app_access_key)
        app_access_key.load_from_conf_env()
        self.assertEqual(app_access_key, self.access_key) 
Example 29
Project: meta-transfer-learning   Author: erfaneshrati   File: run_miniimagenet.py    MIT License 5 votes vote down vote up
def main():
    """
    Load data and train a model on it.
    """
    args = argument_parser().parse_args()
    os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
    os.environ["CUDA_VISIBLE_DEVICES"]=str(args.gpu)

    random.seed(args.seed)

    train_set, val_set, test_set = read_dataset(DATA_DIR)
    if args.metatransfer:
        model = MiniImageNetMetaTransferModel(args.classes, **model_kwargs(args))
    else:
        model = MiniImageNetModel(args.classes, **model_kwargs(args))
    config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)
    config.gpu_options.allow_growth = True

    with tf.Session(config=config) as sess:
        if not args.pretrained:
            print('Training...')
            train(sess, model, train_set, test_set, args.checkpoint, **train_kwargs(args))
        else:
            print('Restoring from checkpoint...')
            tf.train.Saver().restore(sess, tf.train.latest_checkpoint(args.checkpoint))

        print('Evaluating...')
        eval_kwargs = evaluate_kwargs(args)
#        print('Train accuracy: ' + str(evaluate(sess, model, train_set, **eval_kwargs)))
#        print('Validation accuracy: ' + str(evaluate(sess, model, val_set, **eval_kwargs)))
        print('Test accuracy: ' + str(evaluate(sess, model, test_set, **eval_kwargs))) 
Example 30
Project: clikit   Author: sdispater   File: terminal.py    MIT License 5 votes vote down vote up
def _get_terminal_size_linux(self):
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios

                cr = struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))
                return cr
            except:
                pass

        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass

        if not cr:
            try:
                cr = (os.environ["LINES"], os.environ["COLUMNS"])
            except:
                return None

        return int(cr[1]), int(cr[0]) 
Example 31
Project: webnull   Author: macrael   File: webnull.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def reblock_timer(duration, cleanup_func):
    if 'TEST_DURATION' in os.environ:
        duration = float(os.environ['TEST_DURATION'])

    def sigint_handler(signal, frame):
        cleanup_func()
        sys.exit(0)
    signals = [signal.SIGINT, signal.SIGHUP]
    for sig in signals:
        signal.signal(sig, sigint_handler)

    end_time = datetime.datetime.now() + datetime.timedelta(minutes=duration)
    ptime = pretty_time(end_time)
    print('allowed until ' + ptime)

    now = time.time()
    end_time = now + (duration * 60)
    while True:
        remaining = end_time - time.time()
        if remaining <= 0:
            break
        if remaining > 1000:
            time.sleep(10)
        else:
            time.sleep(1)

    cleanup_func() 
Example 32
Project: webnull   Author: macrael   File: webnull.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    if 'DEV_MODE' in os.environ:
        print('Running in Development Mode')

    args = arg_parser().parse_args()
    args.func(args) 
Example 33
Project: mlbv   Author: kmac   File: mlbv.py    GNU General Public License v3.0 5 votes vote down vote up
def display_usage():
    """Displays contents of readme file."""
    current_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
    readme_path = os.path.abspath(os.path.join(current_dir, '..', 'README.md'))
    if not os.path.exists(readme_path):
        print("Could not find documentation file [expected at: {}]".format(readme_path))
        return -1
    if 'PAGER' in os.environ:
        cmd = [os.environ['PAGER'], readme_path]
        subprocess.run(cmd)
    else:
        with open(readme_path, 'r') as infile:
            for line in infile:
                print(line, end='')
    return 0 
Example 34
Project: godot-mono-builds   Author: godotengine   File: desktop.py    MIT License 5 votes vote down vote up
def get_osxcross_sdk(target, osxcross_bin):
    osxcross_sdk = os.environ.get('OSXCROSS_SDK', 14)

    name_fmt = path_join(osxcross_bin, target + '-apple-darwin%s-%s')

    if not 'OSXCROSS_SDK' in os.environ and not os.path.isfile(name_fmt % (osxcross_sdk, 'ar')):
        # Default 14 wasn't it, try 15
        osxcross_sdk = 15

    if not os.path.isfile(name_fmt % (osxcross_sdk, 'ar')):
        raise BuildError('Specify a valid osxcross SDK with the environment variable \'OSXCROSS_SDK\'')

    return osxcross_sdk 
Example 35
Project: godot-mono-builds   Author: godotengine   File: desktop.py    MIT License 5 votes vote down vote up
def strip_libs(opts: DesktopOpts, product: str, target_platform: str, target: str):
    if is_cross_compiling(target_platform):
        if target_platform == 'windows':
            mxe_bin = path_join(opts.mxe_prefix, 'bin')
            name_fmt = path_join(mxe_bin, target + '-w64-mingw32-%s')
            strip = name_fmt % 'strip'
        elif target_platform == 'osx':
            assert 'OSXCROSS_ROOT' in os.environ
            osxcross_root = os.environ['OSXCROSS_ROOT']
            osxcross_bin = path_join(osxcross_bin, 'target', 'bin')
            osxcross_sdk = get_osxcross_sdk(target, osxcross_bin)

            name_fmt = path_join(osxcross_bin, target + ('-apple-darwin%s-' % osxcross_sdk) + '%s')
            strip = name_fmt % 'strip'
    else:
        strip = 'strip'

    install_dir = path_join(opts.install_dir, '%s-%s-%s' % (product, target, opts.configuration))
    out_libs_dir = path_join(install_dir, 'lib')

    lib_files = globs(('*.a', '*.so'), dirpath=out_libs_dir)
    if len(lib_files):
        run_command(strip, args=['--strip-unneeded'] + lib_files, name='strip')

    if target_platform == 'windows':
        out_bin_dir = path_join(install_dir, 'bin')

        dll_files = globs(('*.dll',), dirpath=out_bin_dir)
        if len(dll_files):
            run_command(strip, args=['--strip-unneeded'] + dll_files, name='strip') 
Example 36
Project: godot-mono-builds   Author: godotengine   File: runtime.py    MIT License 5 votes vote down vote up
def run_autogen(opts: RuntimeOpts):
    autogen_env = os.environ.copy()
    autogen_env['NOCONFIGURE'] = '1'

    if not find_executable('glibtoolize') and 'CUSTOM_GLIBTOOLIZE_PATH' in os.environ:
        autogen_env['PATH'] = os.environ['CUSTOM_GLIBTOOLIZE_PATH'] + ':' + autogen_env['PATH']

    run_command(os.path.join(opts.mono_source_root, 'autogen.sh'), cwd=opts.mono_source_root, env=autogen_env, name='autogen') 
Example 37
Project: apm-python-agent-principle   Author: mozillazg   File: agent.py    MIT License 5 votes vote down vote up
def main():
    args = sys.argv[1:]
    os.environ['PYTHONPATH'] = boot_dir
    # 执行后面的 python 程序命令
    # sys.executable 是 python 解释器程序的绝对路径 ``which python``
    # >>> sys.executable
    # '/usr/local/var/pyenv/versions/3.5.1/bin/python3.5'
    os.execl(sys.executable, sys.executable, *args) 
Example 38
Project: pyblish-win   Author: pyblish   File: util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def where(program):
    r"""Parse PATH for executables

    Windows note:
        PATHEXT yields possible suffixes, such as .exe, .bat and .cmd

    Usage:
        >> where("python")
        'c:\\python27\\python.exe'

    """

    suffixes = [""]

    try:
        # Append Windows suffixes, such as .exe, .bat and .cmd
        suffixes.extend(os.environ.get("PATHEXT").split(os.pathsep))
    except:
        pass

    for path in os.environ["PATH"].split(os.pathsep):

        # A path may be empty.
        if not path:
            continue

        for suffix in suffixes:
            full_path = os.path.join(path, program + suffix)
            if os.path.isfile(full_path):
                return full_path 
Example 39
Project: pyblish-win   Author: pyblish   File: _launcher.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setup(root):
    pythonpath = os.path.realpath(os.path.join(root, "..", "pythonpath"))
    pyqtdir = os.path.realpath(os.path.join(root, "..", "lib", "python-qt5"))

    PYTHONPATH = os.environ.get("PYTHONPATH", "")
    os.environ["PYTHONPATH"] = os.pathsep.join(
        [pythonpath, pyqtdir, PYTHONPATH]) 
Example 40
Project: pyblish-win   Author: pyblish   File: __pyblish_util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def install_dependencies():
    """Add PyQt5 to PYTHONPATH"""
    pyqt_path = os.path.join(repository_dir, "lib", "python-qt5")
    assert os.path.isdir(pyqt_path)

    if pyqt_path not in os.environ.get("PYTHONPATH", ""):
        var = pyqt_path + os.pathsep + os.environ.get("PYTHONPATH", "")
        os.environ["PYTHONPATH"] = var

    if pyqt_path not in sys.path:
        sys.path.insert(0, pyqt_path) 
Example 41
Project: pyblish-win   Author: pyblish   File: __pyblish_util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def install_path():
    """Add Python 2.7 to PATH"""
    python_path = os.path.join(repository_dir, "lib", "Python27")
    assert os.path.isdir(python_path)
    if python_path not in os.environ.get("PATH", ""):
        var = python_path + os.pathsep + os.environ.get("PATH", "")
        os.environ["PATH"] = var 
Example 42
Project: pyblish-win   Author: pyblish   File: __pyblish_util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def install_pythonpath():
    """Add Pyblish packages to PYTHONPATH"""
    if pythonpath not in os.environ["PYTHONPATH"]:
        var = pythonpath + os.pathsep + os.environ.get("PYTHONPATH", "")
        os.environ["PYTHONPATH"] = var 
Example 43
Project: pyblish-win   Author: pyblish   File: _osx_support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _remove_universal_flags(_config_vars):
    """Remove all universal build arguments from config vars"""

    for cv in _UNIVERSAL_CONFIG_VARS:
        # Do not alter a config var explicitly overriden by env var
        if cv in _config_vars and cv not in os.environ:
            flags = _config_vars[cv]
            flags = re.sub('-arch\s+\w+\s', ' ', flags)
            flags = re.sub('-isysroot [^ \t]*', ' ', flags)
            _save_modified_value(_config_vars, cv, flags)

    return _config_vars 
Example 44
Project: pyblish-win   Author: pyblish   File: _osx_support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _remove_unsupported_archs(_config_vars):
    """Remove any unsupported archs from config vars"""
    # Different Xcode releases support different sets for '-arch'
    # flags. In particular, Xcode 4.x no longer supports the
    # PPC architectures.
    #
    # This code automatically removes '-arch ppc' and '-arch ppc64'
    # when these are not supported. That makes it possible to
    # build extensions on OSX 10.7 and later with the prebuilt
    # 32-bit installer on the python.org website.

    # skip checks if the compiler was overriden with a CC env variable
    if 'CC' in os.environ:
        return _config_vars

    if re.search('-arch\s+ppc', _config_vars['CFLAGS']) is not None:
        # NOTE: Cannot use subprocess here because of bootstrap
        # issues when building Python itself
        status = os.system(
            """echo 'int main{};' | """
            """'%s' -c -arch ppc -x c -o /dev/null /dev/null 2>/dev/null"""
            %(_config_vars['CC'].replace("'", "'\"'\"'"),))
        if status:
            # The compile failed for some reason.  Because of differences
            # across Xcode and compiler versions, there is no reliable way
            # to be sure why it failed.  Assume here it was due to lack of
            # PPC support and remove the related '-arch' flags from each
            # config variables not explicitly overriden by an environment
            # variable.  If the error was for some other reason, we hope the
            # failure will show up again when trying to compile an extension
            # module.
            for cv in _UNIVERSAL_CONFIG_VARS:
                if cv in _config_vars and cv not in os.environ:
                    flags = _config_vars[cv]
                    flags = re.sub('-arch\s+ppc\w*\s', ' ', flags)
                    _save_modified_value(_config_vars, cv, flags)

    return _config_vars 
Example 45
Project: pyblish-win   Author: pyblish   File: dyld.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def dyld_env(env, var):
    if env is None:
        env = os.environ
    rval = env.get(var)
    if rval is None:
        return []
    return rval.split(':') 
Example 46
Project: pyblish-win   Author: pyblish   File: dyld.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def dyld_image_suffix(env=None):
    if env is None:
        env = os.environ
    return env.get('DYLD_IMAGE_SUFFIX') 
Example 47
Project: pyblish-win   Author: pyblish   File: util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def find_library(name):
        if name in ('c', 'm'):
            return find_msvcrt()
        # See MSDN for the REAL search order.
        for directory in os.environ['PATH'].split(os.pathsep):
            fname = os.path.join(directory, name)
            if os.path.isfile(fname):
                return fname
            if fname.lower().endswith(".dll"):
                continue
            fname = fname + ".dll"
            if os.path.isfile(fname):
                return fname
        return None 
Example 48
Project: pyblish-win   Author: pyblish   File: ntpath.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def expanduser(path):
    """Expand ~ and ~user constructs.

    If user or $HOME is unknown, do nothing."""
    if path[:1] != '~':
        return path
    i, n = 1, len(path)
    while i < n and path[i] not in '/\\':
        i = i + 1

    if 'HOME' in os.environ:
        userhome = os.environ['HOME']
    elif 'USERPROFILE' in os.environ:
        userhome = os.environ['USERPROFILE']
    elif not 'HOMEPATH' in os.environ:
        return path
    else:
        try:
            drive = os.environ['HOMEDRIVE']
        except KeyError:
            drive = ''
        userhome = join(drive, os.environ['HOMEPATH'])

    if i != 1: #~user
        userhome = join(dirname(userhome), path[1:i])

    return userhome + path[i:]


# Expand paths containing shell variable substitutions.
# The following rules apply:
#       - no expansion within single quotes
#       - '$$' is translated into '$'
#       - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
#       - ${varname} is accepted.
#       - $varname is accepted.
#       - %varname% is accepted.
#       - varnames can be made out of letters, digits and the characters '_-'
#         (though is not verified in the ${varname} and %varname% cases)
# XXX With COMMAND.COM you can use any characters in a variable name,
# XXX except '^|<>='. 
Example 49
Project: pyblish-win   Author: pyblish   File: os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _execvpe(file, args, env=None):
    if env is not None:
        func = execve
        argrest = (args, env)
    else:
        func = execv
        argrest = (args,)
        env = environ

    head, tail = path.split(file)
    if head:
        func(file, *argrest)
        return
    if 'PATH' in env:
        envpath = env['PATH']
    else:
        envpath = defpath
    PATH = envpath.split(pathsep)
    saved_exc = None
    saved_tb = None
    for dir in PATH:
        fullname = path.join(dir, file)
        try:
            func(fullname, *argrest)
        except error, e:
            tb = sys.exc_info()[2]
            if (e.errno != errno.ENOENT and e.errno != errno.ENOTDIR
                and saved_exc is None):
                saved_exc = e
                saved_tb = tb 
Example 50
Project: pyblish-win   Author: pyblish   File: os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, environ):
                UserDict.UserDict.__init__(self)
                data = self.data
                for k, v in environ.items():
                    data[k.upper()] = v