Python os.unsetenv() Examples

The following are 30 code examples of os.unsetenv(). 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 os , or try the search function .
Example #1
Source File: _environ.py    From bugatsinho.github.io with GNU General Public License v3.0 6 votes vote down vote up
def unsetenv(key):
    """Like `os.unsetenv` but takes unicode under Windows + Python 2

    Args:
        key (pathlike): The env var to unset
    """

    key = path2fsn(key)
    if is_win:
        # python 3 has no unsetenv under Windows -> use our ctypes one as well
        try:
            del_windows_env_var(key)
        except WindowsError:
            pass
    else:
        os.unsetenv(key) 
Example #2
Source File: mem.py    From Fastir_Collector with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kw):
        if hasattr(sys, 'frozen'):
            # We have to set original _MEIPASS2 value from sys._MEIPASS
            # to get --onefile mode working.
            # Last character is stripped in C-loader. We have to add
            # '/' or '\\' at the end.
            os.putenv('_MEIPASS2', sys._MEIPASS + os.sep)
        try:
            super(_Popen, self).__init__(*args, **kw)
        finally:
            if hasattr(sys, 'frozen'):
                # On some platforms (e.g. AIX) 'os.unsetenv()' is not
                # available. In those cases we cannot delete the variable
                # but only set it to the empty string. The bootloader
                # can handle this case.
                if hasattr(os, 'unsetenv'):
                    os.unsetenv('_MEIPASS2')
                else:
                    os.putenv('_MEIPASS2', '') 
Example #3
Source File: patator_ext.py    From project-black with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, *args, **kw):
      if hasattr(sys, 'frozen'):
        # We have to set original _MEIPASS2 value from sys._MEIPASS
        # to get --onefile mode working.
        os.putenv('_MEIPASS2', sys._MEIPASS)
      try:
        super(_Popen, self).__init__(*args, **kw)
      finally:
        if hasattr(sys, 'frozen'):
          # On some platforms (e.g. AIX) 'os.unsetenv()' is not
          # available. In those cases we cannot delete the variable
          # but only set it to the empty string. The bootloader
          # can handle this case.
          if hasattr(os, 'unsetenv'):
            os.unsetenv('_MEIPASS2')
          else:
            os.putenv('_MEIPASS2', '')

  # Second override 'Popen' class with our modified version. 
Example #4
Source File: compat.py    From ConTroll_Remote_Access_Trojan with Apache License 2.0 6 votes vote down vote up
def system():
    import platform
    # On some Windows installation (Python 2.4) platform.system() is
    # broken and incorrectly returns 'Microsoft' instead of 'Windows'.
    # http://mail.python.org/pipermail/patches/2007-June/022947.html
    syst = platform.system()
    if syst == 'Microsoft':
        return 'Windows'
    return syst


# Set and get environment variables does not handle unicode strings correctly
# on Windows.

# Acting on os.environ instead of using getenv()/setenv()/unsetenv(),
# as suggested in <http://docs.python.org/library/os.html#os.environ>:
# "Calling putenv() directly does not change os.environ, so it's
# better to modify os.environ." (Same for unsetenv.) 
Example #5
Source File: sign-tag.py    From git-repo with Apache License 2.0 6 votes vote down vote up
def sign(opts):
  """Tag the commit & sign it!"""
  # We use ! at the end of the key so that gpg uses this specific key.
  # Otherwise it uses the key as a lookup into the overall key and uses the
  # default signing key.  i.e. It will see that KEYID_RSA is a subkey of
  # another key, and use the primary key to sign instead of the subkey.
  cmd = ['git', 'tag', '-s', opts.tag, '-u', f'{opts.key}!',
         '-m', f'repo {opts.tag}', opts.commit]

  key = 'GNUPGHOME'
  print('+', f'export {key}="{opts.gpgdir}"')
  oldvalue = os.getenv(key)
  os.putenv(key, opts.gpgdir)
  util.run(opts, cmd)
  if oldvalue is None:
    os.unsetenv(key)
  else:
    os.putenv(key, oldvalue) 
Example #6
Source File: resolver_test.py    From hub with Apache License 2.0 6 votes vote down vote up
def testCacheDir(self):
    # No cache dir set, None is returned.
    cache_dir = resolver.tfhub_cache_dir()
    self.assertEqual(cache_dir, None)
    # Use temp dir.
    cache_dir = resolver.tfhub_cache_dir(use_temp=True)
    self.assertEquals(cache_dir,
                      os.path.join(tempfile.gettempdir(), "tfhub_modules"))
    # Use override
    cache_dir = resolver.tfhub_cache_dir(default_cache_dir="/d", use_temp=True)
    self.assertEqual("/d", cache_dir)
    # Use a flag
    FLAGS.tfhub_cache_dir = "/e"
    cache_dir = resolver.tfhub_cache_dir(default_cache_dir="/d", use_temp=True)
    self.assertEqual("/e", cache_dir)
    FLAGS.tfhub_cache_dir = ""
    # Use env variable
    os.environ[resolver._TFHUB_CACHE_DIR] = "/f"
    cache_dir = resolver.tfhub_cache_dir(default_cache_dir="/d", use_temp=True)
    self.assertEqual("/f", cache_dir)
    FLAGS.tfhub_cache_dir = "/e"
    cache_dir = resolver.tfhub_cache_dir(default_cache_dir="/d", use_temp=True)
    self.assertEqual("/f", cache_dir)
    FLAGS.tfhub_cache_dir = ""
    os.unsetenv(resolver._TFHUB_CACHE_DIR) 
Example #7
Source File: EventMonkey.py    From EventMonkey with Apache License 2.0 6 votes vote down vote up
def __init__(self, *args, **kw):
            if hasattr(sys, 'frozen'):
                # We have to set original _MEIPASS2 value from sys._MEIPASS
                # to get --onefile mode working.
                os.putenv('_MEIPASS2', sys._MEIPASS)
            try:
                super(_Popen, self).__init__(*args, **kw)
            finally:
                if hasattr(sys, 'frozen'):
                    # On some platforms (e.g. AIX) 'os.unsetenv()' is not
                    # available. In those cases we cannot delete the variable
                    # but only set it to the empty string. The bootloader
                    # can handle this case.
                    if hasattr(os, 'unsetenv'):
                        os.unsetenv('_MEIPASS2')
                    else:
                        os.putenv('_MEIPASS2', '')

    # Second override 'Popen' class with our modified version. 
Example #8
Source File: patator.py    From patator with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, *args, **kw):
      if hasattr(sys, 'frozen'):
        # We have to set original _MEIPASS2 value from sys._MEIPASS
        # to get --onefile mode working.
        os.putenv('_MEIPASS2', sys._MEIPASS)
      try:
        super(_Popen, self).__init__(*args, **kw)
      finally:
        if hasattr(sys, 'frozen'):
          # On some platforms (e.g. AIX) 'os.unsetenv()' is not
          # available. In those cases we cannot delete the variable
          # but only set it to the empty string. The bootloader
          # can handle this case.
          if hasattr(os, 'unsetenv'):
            os.unsetenv('_MEIPASS2')
          else:
            os.putenv('_MEIPASS2', '')

  # Second override 'Popen' class with our modified version. 
Example #9
Source File: test_config.py    From toot with GNU General Public License v3.0 5 votes vote down vote up
def test_get_config_file_path():
    fn = config.get_config_file_path

    os.unsetenv('XDG_CONFIG_HOME')
    os.environ.pop('XDG_CONFIG_HOME', None)

    assert fn() == os.path.expanduser('~/.config/toot/config.json')

    os.environ['XDG_CONFIG_HOME'] = '/foo/bar/config'

    assert fn() == '/foo/bar/config/toot/config.json'

    os.environ['XDG_CONFIG_HOME'] = '~/foo/config'

    assert fn() == os.path.expanduser('~/foo/config/toot/config.json') 
Example #10
Source File: integration_tests.py    From udocker with Apache License 2.0 5 votes vote down vote up
def test_07_host_env(self, mock_msg):
        """Test passing of host env"""
        if container_not_exists("busyRUN"):
            self.skipTest("no container")
        os.environ["UDOCKER_EXPORTED_VAR"] = "udocker exported var"
        do_run(self, mock_msg,
               [UDOCKER, "run", "--hostenv", "busyRUN", "/bin/env"],
               None, " udocker exported var")
        os.unsetenv("UDOCKER_EXPORTED_VAR") 
Example #11
Source File: e2e_test.py    From hub with Apache License 2.0 5 votes vote down vote up
def test_http_locations(self):
    with tf.Graph().as_default():
      self._generate_module()

      m = hub.Module("http://localhost:%d/test_module.tgz" % self.server_port)
      out = m(11)
      with tf_v1.Session() as sess:
        self.assertAllClose(sess.run(out), 121)

      # Test caching using custom filesystem (file://) to make sure that the
      # TF Hub library can operate on such paths.
      try:
        root_dir = "file://%s" % self.get_temp_dir()
        cache_dir = "%s_%s" % (root_dir, "cache")
        tf_v1.gfile.MakeDirs(cache_dir)
        os.environ["TFHUB_CACHE_DIR"] = cache_dir
        m = hub.Module("http://localhost:%d/test_module.tgz" % self.server_port)
        out = m(11)
        with tf_v1.train.MonitoredSession() as sess:
          self.assertAllClose(sess.run(out), 121)

        cache_content = sorted(tf_v1.gfile.ListDirectory(cache_dir))
        logging.info("Cache context: %s", str(cache_content))
        self.assertEqual(2, len(cache_content))
        self.assertTrue(cache_content[1].endswith(".descriptor.txt"))
        module_files = sorted(tf_v1.gfile.ListDirectory(
            os.path.join(cache_dir, cache_content[0])))
        self.assertListEqual(
            ["assets", "saved_model.pb", "tfhub_module.pb", "variables"],
            module_files)
      finally:
        os.unsetenv("TFHUB_CACHE_DIR") 
Example #12
Source File: deckard.py    From deckard with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setup_faketime(context):
    """
    Setup environment shared between Deckard and binaries under test.

    Environment for child processes must be based on on.environ as modified
    by this function.
    """
    # Set up libfaketime
    os.environ["FAKETIME_NO_CACHE"] = "1"
    os.environ["FAKETIME_TIMESTAMP_FILE"] = os.path.join(context["tmpdir"], ".time")
    os.unsetenv("FAKETIME")

    write_timestamp_file(os.environ["FAKETIME_TIMESTAMP_FILE"],
                         context.get('_OVERRIDE_TIMESTAMP', time.time())) 
Example #13
Source File: tabview.py    From guildai with Apache License 2.0 5 votes vote down vote up
def _patch_os_unsetenv():
    import os

    if not hasattr(os, "unsetenv"):
        os.unsetenv = lambda _val: None 
Example #14
Source File: test_onefile_multiprocess.py    From ConTroll_Remote_Access_Trojan with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kw):
        if hasattr(sys, 'frozen'):
            # We have to get original _MEIPASS2 value from PYTHONPATH
            # to get --onefile and --onedir mode working.
            # Last character is stripped in C-loader.
            os.putenv('_MEIPASS2', sys._MEIPASS)
        try:
            super(_Popen, self).__init__(*args, **kw)
        finally:
            if hasattr(sys, 'frozen'):
                # On some platforms (e.g. AIX) 'os.unsetenv()' is not
                # available. In those cases we cannot delete the variable
                # but only set it to the empty string. The bootloader
                # can handle this case.
                if hasattr(os, 'unsetenv'):
                    os.unsetenv('_MEIPASS2')
                else:
                    os.putenv('_MEIPASS2', '') 
Example #15
Source File: compat.py    From ConTroll_Remote_Access_Trojan with Apache License 2.0 5 votes vote down vote up
def unsetenv(name):
    """
    Delete the environment variable 'name'.
    """
    # Some platforms (e.g. AIX) do not support `os.unsetenv()` and
    # thus `del os.environ[name]` has no effect onto the real
    # environment. For this case we set the value to the empty string.
    os.environ[name] = ""
    del os.environ[name]


# Exec commands in subprocesses. 
Example #16
Source File: base.py    From anybox.recipe.odoo with GNU Affero General Public License v3.0 5 votes vote down vote up
def develop(self, src_directory):
        """Develop the specified source distribution.

        Any call to ``zc.recipe.eggs`` will use that developped version.
        :meth:`develop` launches a subprocess, to which we need to forward
        the paths to requirements via PYTHONPATH.

        :param setup_has_pil: if ``True``, an altered version of setup that
                              does not require PIL is produced to perform the
                              develop, so that installation can be done with
                              ``Pillow`` instead. Recent enough versions of
                              OpenERP/Odoo are directly based on Pillow.
        :returns: project name of the distribution that's been "developed"
                  This is useful for OpenERP/Odoo itself, whose project name
                  changed within the 8.0 stable branch.
        """
        logger.debug("Developing %r", src_directory)
        develop_dir = self.b_options['develop-eggs-directory']
        pythonpath_bak = os.getenv('PYTHONPATH')
        os.putenv('PYTHONPATH', ':'.join(self.recipe_requirements_paths))

        egg_link = zc.buildout.easy_install.develop(src_directory, develop_dir)

        suffix = '.egg-link'

        if pythonpath_bak is None:
            os.unsetenv('PYTHONPATH')
        else:
            os.putenv('PYTHONPATH', pythonpath_bak)

        if not egg_link.endswith(suffix):
            raise RuntimeError(
                "Development of OpenERP/Odoo distribution "
                "produced an unexpected egg link: %r" % egg_link)

        return os.path.basename(egg_link)[:-len(suffix)] 
Example #17
Source File: integration_tests.py    From udocker with Apache License 2.0 5 votes vote down vote up
def test_23_run_reg50(self, mock_msg):
        """Test create, ps, rm"""
        os.environ["UDOCKER_CONTAINERS"] = "/tmp/udocker_containers"
        do_action([UDOCKER, "rm", "busyTMP"])
        do_run(self, mock_msg,
               [UDOCKER, "create", "--name=busyTMP", "busybox"], None, None)
        do_run(self, mock_msg,
               [UDOCKER, "ps"], " busyTMP", None)
        do_run(self, mock_msg,
               [UDOCKER, "ps"], "!busyRUN", None)
        # delete not owner (regression of #50)
        do_run(self, mock_msg,
               [UDOCKER, "rm", "busyTMP"], "!Error", None)
        os.unsetenv("UDOCKER_CONTAINERS") 
Example #18
Source File: cloud_logging_test.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        os.unsetenv('HTTP_X_CLOUD_TRACE_CONTEXT') 
Example #19
Source File: test_kubernetes.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_is_k8s(self):
        os.unsetenv('KUBERNETES_PORT')
        self.assertFalse(detect_is_k8s())
        os.environ['KUBERNETES_PORT'] = '999'
        self.assertTrue(detect_is_k8s()) 
Example #20
Source File: cloud_logging_test.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        os.unsetenv('HTTP_X_CLOUD_TRACE_CONTEXT') 
Example #21
Source File: property_tests.py    From hazelcast-python-client with Apache License 2.0 5 votes vote down vote up
def test_client_properties_with_config_default_value_and_environment_variable(self):
        environ = os.environ
        prop = ClientProperties.HEARTBEAT_INTERVAL
        environ[prop.name] = "1000"

        config = ClientConfig()
        config.set_property(prop.name, 2000)

        props = ClientProperties(config.get_properties())
        self.assertEqual(2, props.get_seconds(prop))
        os.unsetenv(prop.name) 
Example #22
Source File: property_tests.py    From hazelcast-python-client with Apache License 2.0 5 votes vote down vote up
def test_client_properties_with_environment_variable(self):
        environ = os.environ
        environ[ClientProperties.HEARTBEAT_INTERVAL.name] = "3000"

        props = ClientProperties(dict())
        self.assertEqual("3000", props.get(ClientProperties.HEARTBEAT_INTERVAL))
        os.unsetenv(ClientProperties.HEARTBEAT_INTERVAL.name) 
Example #23
Source File: statistics_test.py    From hazelcast-python-client with Apache License 2.0 5 votes vote down vote up
def test_statistics_enabled_with_environment_variable(self):
        environ = os.environ
        environ[ClientProperties.STATISTICS_ENABLED.name] = "true"
        environ[ClientProperties.STATISTICS_PERIOD_SECONDS.name] = str(self.STATS_PERIOD)

        client = HazelcastClient()
        client_uuid = client.cluster.uuid

        time.sleep(2 * self.STATS_PERIOD)
        self._wait_for_statistics_collection(client_uuid)

        os.unsetenv(ClientProperties.STATISTICS_ENABLED.name)
        os.unsetenv(ClientProperties.STATISTICS_PERIOD_SECONDS.name)
        client.shutdown() 
Example #24
Source File: pyi_rth_multiprocessing.py    From pyexe with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kw):
        import os
        import sys

        oldValue = os.getenv('_MEIPASS2')
        os.putenv('_MEIPASS2', sys._MEIPASS)
        try:
            super(_Popen, self).__init__(*args, **kw)
        finally:
            if hasattr(os, 'unsetenv') and oldValue is None:
                os.unsetenv('_MEIPASS2')
            else:
                os.putenv('_MEIPASS2', oldValue or '') 
Example #25
Source File: rth_subprocess.py    From pyexe with Apache License 2.0 5 votes vote down vote up
def _prepare_env(self, args, executable, env):
        import os
        import six
        import sys

        inparam = False
        inenv = False
        origname = None
        if (not isinstance(args, six.string_types) and len(args) >= 1 and
                getattr(sys, '_MEIPASS', None)):
            exename = args[0]
            exelower = exename.lower()
            if exelower.endswith('.exe'):
                exelower = exelower.rsplit('.', 1)[0]
            if (exename == sys.executable or exelower in (
                    'python', 'python%d' % sys.version_info[0],
                    'python%d%d' % (sys.version_info[0], sys.version_info[1]))):
                if env:
                    if '_MEIPASS2' not in env:
                        inparam = True
                        env['_MEIPASS2'] = sys._MEIPASS
                else:
                    inenv = os.getenv('_MEIPASS2', None)
                    os.putenv('_MEIPASS2', sys._MEIPASS)
                origname = exename
                args[0] = sys.executable
        yield
        if origname:
            args[0] = origname
        if inparam:
            del env['_MEIPASS2']
        if inenv is not False:
            if hasattr(os, 'unsetenv') and inenv is None:
                os.unsetenv('_MEIPASS2')
            else:
                os.putenv('_MEIPASS2', inenv or '') 
Example #26
Source File: 13_sockact_test.py    From xmpp-cloud-auth with MIT License 5 votes vote down vote up
def test_no_systemd_at_all(self):
        os.unsetenv('LISTEN_FDS')
        os.unsetenv('LISTEN_PID')
        self.assertEqual(listen_fds_with_names(), None) 
Example #27
Source File: 13_sockact_test.py    From xmpp-cloud-auth with MIT License 5 votes vote down vote up
def test_listen_3_fds_no_names(self):
        os.environ['LISTEN_FDS'] = '3'
        os.environ['LISTEN_PID'] = str(os.getpid())
        os.unsetenv('LISTEN_FDNAMES')
        self.assertEqual(listen_fds_with_names(),
            {3: 'unknown', 4: 'unknown', 5: 'unknown'}) 
Example #28
Source File: 13_sockact_test.py    From xmpp-cloud-auth with MIT License 5 votes vote down vote up
def test_listen_1_fd_no_names(self):
        os.environ['LISTEN_FDS'] = '1'
        os.environ['LISTEN_PID'] = str(os.getpid())
        os.unsetenv('LISTEN_FDNAMES')
        self.assertEqual(listen_fds_with_names(),
            {3: 'unknown'}) 
Example #29
Source File: 13_sockact_test.py    From xmpp-cloud-auth with MIT License 5 votes vote down vote up
def test_listen_no_fds(self):
        os.unsetenv('LISTEN_FDS')
        os.unsetenv('LISTEN_PID')
        self.assertEqual(listen_fds_with_names(), None) 
Example #30
Source File: test_config.py    From bubuku with MIT License 5 votes vote down vote up
def test_zk_prefix_replacement():
    if os.getenv('ZOOKEEPER_PREFIX', None):
        os.unsetenv('ZOOKEEPER_PREFIX')
    assert load_config().zk_prefix == '/'

    os.environ['ZOOKEEPER_PREFIX'] = '/'
    assert load_config().zk_prefix == '/'

    os.environ['ZOOKEEPER_PREFIX'] = 'test'
    assert load_config().zk_prefix == '/test'

    os.environ['ZOOKEEPER_PREFIX'] = '/test'
    assert load_config().zk_prefix == '/test'