Python os.chdir() Examples

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

Example 1
Project: charm-plumgrid-gateway   Author: openstack   File: utils.py    (Apache License 2.0) View Source Project 7 votes vote down vote up
def _git_update_requirements(venv, package_dir, reqs_dir):
    """
    Update from global requirements.

    Update an OpenStack git directory's requirements.txt and
    test-requirements.txt from global-requirements.txt.
    """
    orig_dir = os.getcwd()
    os.chdir(reqs_dir)
    python = os.path.join(venv, 'bin/python')
    cmd = [python, 'update.py', package_dir]
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError:
        package = os.path.basename(package_dir)
        error_out("Error updating {} from "
                  "global-requirements.txt".format(package))
    os.chdir(orig_dir) 
Example 2
Project: py_find_1st   Author: roebel   File: ez_setup.py    (GNU General Public License v3.0) View Source Project 7 votes vote down vote up
def archive_context(filename):
    # extracting the archive
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        with get_zip_class()(filename) as archive:
            archive.extractall()

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)
        yield

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir) 
Example 3
Project: NeoAnalysis   Author: neoanalysis   File: shell.py    (license) View Source Project 7 votes vote down vote up
def shell(cmd):
    """Run each line of a shell script; raise an exception if any line returns
    a nonzero value.
    """
    pin, pout = os.pipe()
    proc = sp.Popen('/bin/bash', stdin=sp.PIPE)
    for line in cmd.split('\n'):
        line = line.strip()
        if line.startswith('#'):
            print('\033[33m> ' + line + '\033[0m')
        else:
            print('\033[32m> ' + line + '\033[0m')
        if line.startswith('cd '):
            os.chdir(line[3:])
        proc.stdin.write((line + '\n').encode('utf-8'))
        proc.stdin.write(('echo $? 1>&%d\n' % pout).encode('utf-8'))
        ret = ""
        while not ret.endswith('\n'):
            ret += os.read(pin, 1)
        ret = int(ret.strip())
        if ret != 0:
            print("\033[31mLast command returned %d; bailing out.\033[0m" % ret)
            sys.exit(-1)
    proc.stdin.close()
    proc.wait() 
Example 4
Project: rpwng   Author: MrNbaYoh   File: builder_base.py    (license) View Source Project 6 votes vote down vote up
def build(self, file):
        if self.built:
            raise PermissionError("You cannot build multiple times!")

        if not self.loaded:
            self.load(file)

        old = os.getcwd()
        sys.path.append(os.path.dirname(os.path.abspath(file)))  # for module import that aren't "include" call
        try:
            content = open(file, "rb").read()
            os.chdir(os.path.dirname(os.path.abspath(file)))  # set the current working directory, for open() etc.
            exec(compile(content, file, 'exec'), self.user_functions)
        except Exception as err:
            print("An exception occured while building: ", file=sys.stderr)
            lines = traceback.format_exc(None, err).splitlines()
            print("  " + lines[-1], file=sys.stderr)
            for l in lines[3:-1]:
                print(l, file=sys.stderr)
            exit(1)

        os.chdir(old)
        sys.path.remove(os.path.dirname(os.path.abspath(file)))
        self.built = True 
Example 5
Project: rpwng   Author: MrNbaYoh   File: builder_base.py    (license) View Source Project 6 votes vote down vote up
def load(self, file):
        if self.loaded:
            return

        sys.path.append(os.path.dirname(os.path.abspath(file)))  # for module import that aren't "include" call
        old = os.getcwd()
        try:
            content = open(file, "rb").read()
            os.chdir(os.path.dirname(os.path.abspath(file)))  # set the current working directory, for open() etc.
            exec(compile(content, file, 'exec'), self.user_functions)
        except Exception as err:
            print("An exception occured while loading: ", file=sys.stderr)
            lines = traceback.format_exc(None, err).splitlines()
            print("  " + lines[-1], file=sys.stderr)
            for l in lines[3:-1]:
                print(l, file=sys.stderr)
            exit(1)

        os.chdir(old)
        sys.path.remove(os.path.dirname(os.path.abspath(file)))
        self.loaded = True
        self.mem_offset = 0 
Example 6
Project: Adafruit_Python_PureIO   Author: adafruit   File: ez_setup.py    (MIT License) View Source Project 6 votes vote down vote up
def archive_context(filename):
    # extracting the archive
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        with get_zip_class()(filename) as archive:
            archive.extractall()

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)
        yield

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir) 
Example 7
Project: Adafruit_Python_PCA9685   Author: adafruit   File: ez_setup.py    (MIT License) View Source Project 6 votes vote down vote up
def archive_context(filename):
    # extracting the archive
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        with get_zip_class()(filename) as archive:
            archive.extractall()

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)
        yield

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir) 
Example 8
Project: Python   Author: Guzi219   File: qiushimm.py    (license) View Source Project 6 votes vote down vote up
def init_work_dir(self):
        retval = os.getcwd()
        print '#current dir is : ' + retval
        # ??????
        store_dir = retval + os.sep + 'tmp'
        print '#all imgs are going to be stored in dir :' + store_dir

        if not os.path.exists(store_dir):
            print '#tmp dir does not exist, attemp to mkdir'
            os.mkdir(store_dir)
            print '#mkdir sucessfully'
        else:
            print '#tmp dir is already exist'

        self.store_dir = store_dir

        # print '#now change current dir to tmp'
        # os.chdir(store_dir) #no neccessary
        # print os.getcwd() 
Example 9
Project: Python   Author: Guzi219   File: qiubaiadult.py    (license) View Source Project 6 votes vote down vote up
def init_work_dir(self):
        retval = os.getcwd()
        print '#current dir is : ' + retval
        # ??????
        store_dir = retval + os.sep + 'tmp'
        print '#all imgs are going to be stored in dir :' + store_dir

        if not os.path.exists(store_dir):
            print '#tmp dir does not exist, attemp to mkdir'
            os.mkdir(store_dir)
            print '#mkdir sucessfully'
        else:
            print '#tmp dir is already exist'

        self.store_dir = store_dir

        # print '#now change current dir to tmp'
        # os.chdir(store_dir) #no neccessary
        # print os.getcwd() 
Example 10
Project: ardy   Author: avara1986   File: invoke.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _run_local_lambda(self, lambda_config):
        prev_folder = os.getcwd()
        os.chdir(self.config.get_projectdir())
        sys.path.append(self.config.get_projectdir())
        lambda_name = lambda_config["FunctionName"]
        lambda_handler = self.import_function(lambda_config["Handler"])

        # Run and set a counter
        start = time.time()
        results = lambda_handler({}, MockContext(lambda_name))
        end = time.time()

        # restore folder
        os.chdir(prev_folder)

        # Print results
        logger.info("{0}".format(results))
        logger.info("\nexecution time: {:.8f}s\nfunction execution "
                    "timeout: {:2}s".format(end - start, lambda_config["Timeout"])) 
Example 11
Project: NeoVintageous   Author: NeoVintageous   File: ex_actions.py    (license) View Source Project 6 votes vote down vote up
def _changing_cd(f, *args, **kwargs):
    def inner(*args, **kwargs):
        try:
            state = State(args[0].view)
        except AttributeError:
            state = State(args[0].window.active_view())

        old = os.getcwd()
        try:
            # FIXME: Under some circumstances, like when switching projects to
            # a file whose _cmdline_cd has not been set, _cmdline_cd might
            # return 'None'. In such cases, change to the actual current
            # directory as a last measure. (We should probably fix this anyway).
            os.chdir(state.settings.vi['_cmdline_cd'] or old)
            f(*args, **kwargs)
        finally:
            os.chdir(old)

    return inner 
Example 12
Project: Home-Assistant   Author: jmart518   File: configurator.py    (MIT License) View Source Project 6 votes vote down vote up
def main(args):
    global HTTPD, CREDENTIALS
    if args:
        load_settings(args[0])
    print("Starting server")
    server_address = (LISTENIP, LISTENPORT)
    if CREDENTIALS:
        CREDENTIALS = base64.b64encode(bytes(CREDENTIALS, "utf-8"))
        Handler = AuthHandler
    else:
        Handler = RequestHandler
    if not SSL_CERTIFICATE:
        HTTPD = HTTPServer(server_address, Handler)
    else:
        HTTPD = socketserver.TCPServer(server_address, Handler)
        HTTPD.socket = ssl.wrap_socket(HTTPD.socket,
                                       certfile=SSL_CERTIFICATE,
                                       keyfile=SSL_KEY,
                                       server_side=True)
    print('Listening on: %s://%s:%i' % ('https' if SSL_CERTIFICATE else 'http',
                                        LISTENIP,
                                        LISTENPORT))
    if BASEPATH:
        os.chdir(BASEPATH)
    HTTPD.serve_forever() 
Example 13
Project: charm-swift-proxy   Author: openstack   File: utils.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _git_update_requirements(venv, package_dir, reqs_dir):
    """
    Update from global requirements.

    Update an OpenStack git directory's requirements.txt and
    test-requirements.txt from global-requirements.txt.
    """
    orig_dir = os.getcwd()
    os.chdir(reqs_dir)
    python = os.path.join(venv, 'bin/python')
    cmd = [python, 'update.py', package_dir]
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError:
        package = os.path.basename(package_dir)
        error_out("Error updating {} from "
                  "global-requirements.txt".format(package))
    os.chdir(orig_dir) 
Example 14
Project: charm-swift-proxy   Author: openstack   File: utils.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _git_update_requirements(venv, package_dir, reqs_dir):
    """
    Update from global requirements.

    Update an OpenStack git directory's requirements.txt and
    test-requirements.txt from global-requirements.txt.
    """
    orig_dir = os.getcwd()
    os.chdir(reqs_dir)
    python = os.path.join(venv, 'bin/python')
    cmd = [python, 'update.py', package_dir]
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError:
        package = os.path.basename(package_dir)
        error_out("Error updating {} from "
                  "global-requirements.txt".format(package))
    os.chdir(orig_dir) 
Example 15
Project: acbs   Author: AOSC-Dev   File: acbs_start_build.py    (license) View Source Project 6 votes vote down vote up
def copy_abd(tmp_dir_loc, repo_dir, pkg_info):
    if pkg_info['SUBDIR'] != '':
        try:
            os.chdir(pkg_info['SUBDIR'])
        except:
            err_msg('Failed to enter sub-directory!')
            return False
    else:
        try:
            os.chdir(pkg_info['NAME'] + '-' + pkg_info['VER'])
        except:
            try:
                os.chdir(pkg_info['NAME'])
            except:
                err_msg(
                    'Failed to determine sub-directory, please specify manually.')
                return False
    try:
        shutil.copytree(repo_dir,
                        os.path.abspath(os.path.curdir) + '/autobuild/', symlinks=True)
    except:
        err_msg('Error occurred when copying files from tree!')
        return False
    return True 
Example 16
Project: acbs   Author: AOSC-Dev   File: acbs_start_build.py    (license) View Source Project 6 votes vote down vote up
def start_ab3(tmp_dir_loc, repo_dir, pkg_info, rm_abdir=False):
    start_time = int(time.time())
    os.chdir(tmp_dir_loc)
    if not copy_abd(tmp_dir_loc, repo_dir, pkg_info):
        return False
    # For logging support: ptyprocess.PtyProcessUnicode.spawn(['autobuild'])
    shadow_defines_loc = os.path.abspath(os.path.curdir)
    if not parser_pass_through(pkg_info, shadow_defines_loc):
        return False
    try:
        subprocess.check_call(['autobuild'])
    except:
        return False
    time_span = int(time.time()) - start_time
    print('>>>>>>>>>>>>>>>>>> Time for building\033[36m {} \033[0m:\033[36m {} \033[0mseconds'.format(
        pkg_info['NAME'], time_span))
    if rm_abdir is True:
        shutil.rmtree(os.path.abspath(os.path.curdir) + '/autobuild/')
    # Will get better display later
    return True 
Example 17
Project: acbs   Author: AOSC-Dev   File: acbs-build.py    (license) View Source Project 6 votes vote down vote up
def init_env(tree=['default']):
    dump_loc = '/var/cache/acbs/tarballs/'
    tmp_loc = '/var/cache/acbs/build/'
    print("----- Welcome to ACBS - %s -----" % (acbs_version))
    try:
        if not os.path.isdir(dump_loc):
            os.makedirs(dump_loc)
        if not os.path.isdir(tmp_loc):
            os.makedirs(tmp_loc)
    except:
        raise IOError('\033[93mFailed to make work directory\033[0m!')
    if os.path.exists('/etc/acbs_forest.conf'):
        tree_loc = parse_acbs_conf(tree[0])
        if tree_loc is not None:
            os.chdir(tree_loc)
        else:
            sys.exit(1)
    else:
        if not write_acbs_conf():
            sys.exit(1)
    return 
Example 18
Project: BackManager   Author: linuxyan   File: ez_setup.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def archive_context(filename):
    """
    Unzip filename to a temporary directory, set to the cwd.

    The unzipped target is cleaned up after.
    """
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        with ContextualZipFile(filename) as archive:
            archive.extractall()

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)
        yield

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir) 
Example 19
Project: cmake.nvim   Author: phillipbonhomme   File: test_cmake.py    (The Unlicense) View Source Project 6 votes vote down vote up
def test_RTagsDaemonStartClean(self):
        try:
            os.chdir("clean")
        except OSError:
            print("Test Error: Couldn't cd into 'dirty' test directory.")
            raise
        self.assertFalse(self.cmake_build_info["build_dir"].is_dir())
        self.plugin.setup_rtags_daemon()
        try:
            rtags_daemon_status = subprocess.check_output(
                self.cmake_cmd_info["rtags_status"])
        except subprocess.CalledProcessError as e:
            print(e.output)
        self.assertTrue(
            len("*********************************\nfileids\n*********************************\n*********************************\nheadererrors\n*********************************\n*********************************\ninfo\n*********************************\nRunning a release build\nsocketFile: /Users/phillipbonhomme/.rdm\ndataDir: /Users/phillipbonhomme/.cache/rtags/\noptions: 0x14jobCount: 4\nrpVisitFileTimeout: 60000\nrpIndexDataMessageTimeout: 60000\nrpConnectTimeout: 0\nrpConnectTimeout: 0\ndefaultArguments: List<String>(-ferror-limit=50, -Wall, -fspell-checking, -Wno-unknown-warning-option\")\nincludePaths: List<Source::Include>(\")\ndefines: List<Source::Define>(-DRTAGS=\")\nignoredCompilers: Set<Path>(\")\n*********************************\njobs\n*********************************\n"
                ) <= len(str(rtags_daemon_status))) 
Example 20
Project: cmake.nvim   Author: phillipbonhomme   File: test_cmake.py    (The Unlicense) View Source Project 6 votes vote down vote up
def test_RTagsClientStartDirty(self):
        try:
            os.chdir("dirty")
        except OSError:
            print("Test Error: Couldn't cd into 'dirty' test directory.")
            raise
        self.assertTrue(self.cmake_build_info["build_dir"].is_dir())
        self.assertTrue(self.cmake_build_info["comp_data_cmake"].is_file())
        self.plugin.setup_rtags_daemon()
        self.plugin.connect_rtags_client()
        try:
            rtags_client_status = subprocess.check_output(
                self.cmake_cmd_info["rtags_file_status"] +
                [str(src_info["cpp"])])
        except subprocess.CalledProcessError as e:
            print(e.output)
        self.assertTrue(str(rtags_client_status).find("managed"))
        try:
            rtags_client_status = subprocess.check_output(
                self.cmake_cmd_info["rtags_file_status"] +
                [str(src_info["test_cpp"])])
        except subprocess.CalledProcessError as e:
            print(e.output)
        self.assertTrue(str(rtags_client_status).find("managed")) 
Example 21
Project: cmake.nvim   Author: phillipbonhomme   File: test_cmake.py    (The Unlicense) View Source Project 6 votes vote down vote up
def test_RTagsClientSetFile(self):
        try:
            os.chdir("dirty")
        except OSError:
            print("Test Error: Couldn't cd into 'dirty' test directory.")
            raise
        self.assertTrue(self.cmake_build_info["build_dir"].is_dir())
        self.assertTrue(self.cmake_build_info["comp_data_cmake"].is_file())
        self.plugin.setup_rtags_daemon()
        self.plugin.connect_rtags_client()
        self.plugin.rtags_set_file([str(src_info["cpp"])])
        try:
            rtags_client_status = subprocess.check_output(
                self.cmake_cmd_info["rtags_file_status"] +
                [str(src_info["cpp"])])
        except subprocess.CalledProcessError as e:
            print(e.output)
        self.assertTrue(str(rtags_client_status).find("managed")) 
Example 22
Project: cmake.nvim   Author: phillipbonhomme   File: test_cmake.py    (The Unlicense) View Source Project 6 votes vote down vote up
def test_RTagsClientUpdateBuffers(self):
        try:
            os.chdir("dirty")
        except OSError:
            print("Test Error: Couldn't cd into 'dirty' test directory.")
            raise
        self.assertTrue(self.cmake_build_info["build_dir"].is_dir())
        self.assertTrue(self.cmake_build_info["comp_data_cmake"].is_file())
        self.plugin.setup_rtags_daemon()
        self.plugin.connect_rtags_client()
        self.plugin.update_rtags_buffers(
            [str(src_info["test_cpp"]),
             str(src_info["cpp"])])
        try:
            rtags_client_status = subprocess.check_output(
                self.cmake_cmd_info["rtags_buffers"])
        except subprocess.CalledProcessError as e:
            print(e.output)
        filepath = os.getcwd() + str(src_info["test_cpp"])
        self.assertTrue(str(rtags_client_status).find(filepath)) 
Example 23
Project: cmake.nvim   Author: phillipbonhomme   File: test_cmake.py    (The Unlicense) View Source Project 6 votes vote down vote up
def test_RTagsDaemonSink(self):
        try:
            os.chdir("dirty")
        except OSError:
            print("Test Error: Couldn't cd into 'dirty' test directory.")
            raise
        self.assertTrue(self.cmake_build_info["build_dir"].is_dir())
        self.assertTrue(self.cmake_build_info["comp_data_cmake"].is_file())
        self.plugin.setup_rtags_daemon()
        self.plugin.connect_rtags_client()
        self.plugin.update_rtags_buffers(
            [str(src_info["test_cpp"]),
             str(src_info["cpp"])])
        try:
            rtags_client_status = subprocess.check_output(
                self.cmake_cmd_info["rtags_buffers"])
        except subprocess.CalledProcessError as e:
            print(e.output) 
Example 24
Project: ovn-kubernetes-charm   Author: AakashKT   File: ovn.py    (license) View Source Project 6 votes vote down vote up
def initialise_worker(cni):
    status_set('maintenance', 'Initialising worker network');

    local_ip = get_my_ip();
    worker_subnet = retrieve('worker_subnet');
    central_ip = retrieve('central_ip');
    hostname = run_command('hostname').replace('\n', '');

    run_command('ovs-vsctl set Open_vSwitch . \
                external_ids:k8s-api-server="%s:8080"' % (central_ip));
    run_command('ovn-k8s-overlay minion-init --cluster-ip-subnet="192.168.0.0/16" \
                    --minion-switch-subnet="%s" --node-name="%s"' % (worker_subnet, hostname));

    os.chdir('/tmp/');
    run_command('wget https://github.com/containernetworking/cni/releases/download/v0.5.2/cni-amd64-v0.5.2.tgz');
    run_command('sudo mkdir -p /opt/cni/bin');
    run_command('sudo mkdir -p /etc/cni/net.d');
    os.chdir('/opt/cni/bin/');
    run_command('sudo tar xvzf /tmp/cni-amd64-v0.5.2.tgz');

    status_set('active', 'Worker subnet : %s' % (worker_subnet));
    set_state('worker.initialised'); 
Example 25
Project: ovn-kubernetes-charm   Author: AakashKT   File: ovn.py    (license) View Source Project 6 votes vote down vote up
def send_cert(cni, mconfig):
    worker_hostname = run_command('hostname');
    mconfig.set_worker_id(worker_hostname);

    os.chdir('/etc/openvswitch');
    run_command('sudo ovs-pki req ovncontroller');

    req_file = open('ovncontroller-req.pem', 'r');
    cert = req_file.read();
    mconfig.send_worker_data({
        'cert_to_sign': cert,
        'worker_hostname': worker_hostname
    });

    status_set('maintenance', 'Waiting for certificate');
    set_state('worker.cert.sent'); 
Example 26
Project: Adafruit_Python_ADS1x15   Author: adafruit   File: ez_setup.py    (MIT License) View Source Project 6 votes vote down vote up
def archive_context(filename):
    # extracting the archive
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        with get_zip_class()(filename) as archive:
            archive.extractall()

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)
        yield

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir) 
Example 27
Project: ccu_and_eccu_publish   Author: gaofubin   File: ez_setup.py    (license) View Source Project 6 votes vote down vote up
def archive_context(filename):
    # extracting the archive
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        with ContextualZipFile(filename) as archive:
            archive.extractall()

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)
        yield

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir) 
Example 28
Project: bob   Author: BobBuildTool   File: test_input_recipeset.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def testDefaultIncludeOverrides(self):
        """Test that included files override settings of default.yaml"""
        with TemporaryDirectory() as tmp:
            os.chdir(tmp)
            os.mkdir("recipes")
            with open("default.yaml", "w") as f:
                f.write("include:\n")
                f.write("    - user\n")
                f.write("environment:\n")
                f.write("    FOO: BAR\n")
                f.write("    BAR: BAZ\n")
            with open("user.yaml", "w") as f:
                f.write("environment:\n")
                f.write("    FOO: BAZ\n")
            recipeSet = RecipeSet()
            recipeSet.parse()

            assert recipeSet.defaultEnv() == { "FOO":"BAZ", "BAR":"BAZ" } 
Example 29
Project: bob   Author: BobBuildTool   File: test_input_recipeset.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def testUserConfigOverrides(self):
        """Test that user configs override default.yaml w/ includes"""
        with TemporaryDirectory() as tmp:
            os.chdir(tmp)
            os.mkdir("recipes")
            with open("default.yaml", "w") as f:
                f.write("include:\n")
                f.write("    - included\n")
                f.write("environment:\n")
                f.write("    FOO: BAR\n")
            with open("included.yaml", "w") as f:
                f.write("environment:\n")
                f.write("    FOO: BAZ\n")
            with open("user.yaml", "w") as f:
                f.write("environment:\n")
                f.write("    FOO: USER\n")

            recipeSet = RecipeSet()
            recipeSet.setConfigFiles(["user"])
            recipeSet.parse()

            assert recipeSet.defaultEnv() == { "FOO":"USER"} 
Example 30
Project: Adafruit_Python_MCP4725   Author: adafruit   File: ez_setup.py    (MIT License) View Source Project 6 votes vote down vote up
def archive_context(filename):
    # extracting the archive
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        with get_zip_class()(filename) as archive:
            archive.extractall()

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)
        yield

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir) 
Example 31
Project: QUANTAXIS   Author: yutiansut   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def sourcecpy(src, des):
    src = os.path.normpath(src)
    des = os.path.normpath(des)
    if not os.path.exists(src) or not os.path.exists(src):
        print("folder is not exist")
        sys.exit(1)
    # ?????????????????????????
    os.chdir(src)
    src_file = [os.path.join(src, file) for file in os.listdir()]
    for source in src_file:
        # ????
        if os.path.isfile(source):
            shutil.copy(source, des)  # ????????????????
        # ????
        if os.path.isdir(source):
            p, src_name = os.path.split(source)
            des = os.path.join(des, src_name)
            shutil.copytree(source, des)  # ??????????????????

# ??CLI????? 
Example 32
Project: NeoAnalysis   Author: neoanalysis   File: shell.py    (license) View Source Project 6 votes vote down vote up
def shell(cmd):
    """Run each line of a shell script; raise an exception if any line returns
    a nonzero value.
    """
    pin, pout = os.pipe()
    proc = sp.Popen('/bin/bash', stdin=sp.PIPE)
    for line in cmd.split('\n'):
        line = line.strip()
        if line.startswith('#'):
            print('\033[33m> ' + line + '\033[0m')
        else:
            print('\033[32m> ' + line + '\033[0m')
        if line.startswith('cd '):
            os.chdir(line[3:])
        proc.stdin.write((line + '\n').encode('utf-8'))
        proc.stdin.write(('echo $? 1>&%d\n' % pout).encode('utf-8'))
        ret = ""
        while not ret.endswith('\n'):
            ret += os.read(pin, 1)
        ret = int(ret.strip())
        if ret != 0:
            print("\033[31mLast command returned %d; bailing out.\033[0m" % ret)
            sys.exit(-1)
    proc.stdin.close()
    proc.wait() 
Example 33
Project: Projects   Author: it2school   File: macosx.py    (license) View Source Project 6 votes vote down vote up
def Video_AutoInit():
    """This is a function that's called from the c extension code
       just before the display module is initialized"""
    if MacOS and not MacOS.WMAvailable():
        if not sdlmain_osx.WMEnable():
            raise ImportError("Can not access the window manager.  Use py2app or execute with the pythonw script.")
    if not sdlmain_osx.RunningFromBundleWithNSApplication():
        try:
            default_icon_data = getResource('pygame_icon.tiff').read()
        except IOError:
            default_icon_data = None
        except NotImplementedError:
            default_icon_data = None

        sdlmain_osx.InstallNSApplication(default_icon_data)
    if (os.getcwd() == '/') and len(sys.argv) > 1:
        os.chdir(os.path.dirname(sys.argv[0]))
    return True 
Example 34
Project: Flask_Blog   Author: sugarguo   File: environment.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def setUp(self):
        if self.datafile is None or self.dataname is None:
            return

        if not os.path.isfile(self.datafile):
            self.old_cwd = None
            return

        self.old_cwd = os.getcwd()

        self.temp_dir = tempfile.mkdtemp()
        zip_file, source, target = [None, None, None]
        try:
            zip_file = zipfile.ZipFile(self.datafile)
            for files in zip_file.namelist():
                _extract(zip_file, files, self.temp_dir)
        finally:
            if zip_file:
                zip_file.close()
            del zip_file

        os.chdir(os.path.join(self.temp_dir, self.dataname)) 
Example 35
Project: Flask_Blog   Author: sugarguo   File: test_upload_docs.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def setUp(self):
        self.dir = tempfile.mkdtemp()
        setup = os.path.join(self.dir, 'setup.py')
        f = open(setup, 'w')
        f.write(SETUP_PY)
        f.close()
        self.old_cwd = os.getcwd()
        os.chdir(self.dir)

        self.upload_dir = os.path.join(self.dir, 'build')
        os.mkdir(self.upload_dir)

        # A test document.
        f = open(os.path.join(self.upload_dir, 'index.html'), 'w')
        f.write("Hello world.")
        f.close()

        # An empty folder.
        os.mkdir(os.path.join(self.upload_dir, 'empty'))

        if sys.version >= "2.6":
            self.old_base = site.USER_BASE
            site.USER_BASE = upload_docs.USER_BASE = tempfile.mkdtemp()
            self.old_site = site.USER_SITE
            site.USER_SITE = upload_docs.USER_SITE = tempfile.mkdtemp() 
Example 36
Project: Flask_Blog   Author: sugarguo   File: test_sdist.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def setUp(self):
        self.temp_dir = tempfile.mkdtemp()
        f = open(os.path.join(self.temp_dir, 'setup.py'), 'w')
        f.write(SETUP_PY)
        f.close()
        # Set up the rest of the test package
        test_pkg = os.path.join(self.temp_dir, 'sdist_test')
        os.mkdir(test_pkg)
        # *.rst was not included in package_data, so c.rst should not be
        # automatically added to the manifest when not under version control
        for fname in ['__init__.py', 'a.txt', 'b.txt', 'c.rst']:
            # Just touch the files; their contents are irrelevant
            open(os.path.join(test_pkg, fname), 'w').close()

        self.old_cwd = os.getcwd()
        os.chdir(self.temp_dir) 
Example 37
Project: Flask_Blog   Author: sugarguo   File: test_develop.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def setUp(self):
        if sys.version < "2.6" or hasattr(sys, 'real_prefix'):
            return

        # Directory structure
        self.dir = tempfile.mkdtemp()
        os.mkdir(os.path.join(self.dir, 'foo'))
        # setup.py
        setup = os.path.join(self.dir, 'setup.py')
        f = open(setup, 'w')
        f.write(SETUP_PY)
        f.close()
        self.old_cwd = os.getcwd()
        # foo/__init__.py
        init = os.path.join(self.dir, 'foo', '__init__.py')
        f = open(init, 'w')
        f.write(INIT_PY)
        f.close()

        os.chdir(self.dir)
        self.old_base = site.USER_BASE
        site.USER_BASE = tempfile.mkdtemp()
        self.old_site = site.USER_SITE
        site.USER_SITE = tempfile.mkdtemp() 
Example 38
Project: Flask_Blog   Author: sugarguo   File: test_develop.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def notest_develop_with_setup_requires(self):

        wanted = ("Could not find suitable distribution for "
                  "Requirement.parse('I-DONT-EXIST')")
        old_dir = os.getcwd()
        os.chdir(self.dir)
        try:
            try:
                dist = Distribution({'setup_requires': ['I_DONT_EXIST']})
            except DistutilsError:
                e = sys.exc_info()[1]
                error = str(e)
                if error ==  wanted:
                    pass
        finally:
            os.chdir(old_dir) 
Example 39
Project: charm-plumgrid-gateway   Author: openstack   File: host.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def chdir(directory):
    """Change the current working directory to a different directory for a code
    block and return the previous directory after the block exits. Useful to
    run commands from a specificed directory.

    :param str directory: The directory path to change to for this context.
    """
    cur = os.getcwd()
    try:
        yield os.chdir(directory)
    finally:
        os.chdir(cur) 
Example 40
Project: Stitch   Author: nathanlopez   File: stitch_utils.py    (license) View Source Project 5 votes vote down vote up
def find_path(text, line, begidx, endidx, \
                dir_only=False, files_only=False, exe_only=False,\
                py_only=False, uploads=False, all_dir=False):
    cur_dir = os.getcwd()
    before_arg = line.rfind(" ", 0, begidx)
    if before_arg == -1:
        return # arg not found

    fixed = line[before_arg+1:begidx]  # fixed portion of the arg
    arg = line[before_arg+1:endidx]

    if uploads:
        os.chdir(uploads_path)
    pattern = arg + '*'

    completions = []
    for path in glob.glob(pattern):
        if dir_only:
            if os.path.isdir(path):
                path = append_slash_if_dir(path)
                completions.append(path.replace(fixed, "", 1))
        elif files_only:
            if not os.path.isdir(path):
                completions.append(path.replace(fixed, "", 1))
        elif exe_only:
            if not os.path.isdir(path):
                if path.endswith('.exe') or path.endswith('.py'):
                    completions.append(path.replace(fixed, "", 1))
        elif py_only:
            if not os.path.isdir(path):
                if path.endswith('.py'):
                    completions.append(path.replace(fixed, "", 1))
        elif all_dir:
            if os.path.isdir(path):
                path = append_slash_if_dir(path)
            completions.append(path.replace(fixed, "", 1))

    os.chdir(cur_dir)
    return completions 
Example 41
Project: pyupdater-wx-demo   Author: wettenhj   File: test_freeze_update_available.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def tearDown(self):
        """
        Clean up.
        """
        wxupdatedemo.__version__ = self.originalVersion
        try:
            shutil.rmtree(self.tempDir)
        except OSError:
            logger.warning("Couldn't remove %s", self.tempDir)
        os.chdir(self.initialWorkingDir)
        try:
            shutil.rmtree(self.fileServerDir)
        except OSError:
            logger.warning("Couldn't remove %s", self.fileServerDir)
        del os.environ['PYUPDATER_FILESERVER_DIR']
        del os.environ['WXUPDATEDEMO_TESTING']
        del os.environ['WXUPDATEDEMO_TESTING_FROZEN']
        del os.environ['WXUPDATEDEMO_TESTING_APP_NAME']
        del os.environ['WXUPDATEDEMO_TESTING_COMPANY_NAME']
        del os.environ['WXUPDATEDEMO_TESTING_APP_VERSION']
        del os.environ['WXUPDATEDEMO_TESTING_PUBLIC_KEY']
        if os.path.exists(appdirs.user_data_dir(APP_NAME, COMPANY_NAME)):
            try:
                shutil.rmtree(appdirs.user_data_dir(APP_NAME, COMPANY_NAME))
            except OSError:
                logger.warning("Couldn't remove %s",
                               appdirs.user_data_dir(APP_NAME, COMPANY_NAME)) 
Example 42
Project: SublimeText2-laravel5.2-artisan-cli   Author: Rotron   File: SublimeArtisan.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def run(self, edit):

		folder = self.view.window().folders()[0]
		os.chdir(folder)

		self.view.window().run_command("exec", {
			"cmd" : ["php artisan help"],
			"shell" : True,
			"working_dir" : folder}) 
Example 43
Project: SublimeText2-laravel5.2-artisan-cli   Author: Rotron   File: SublimeArtisan.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def run(self, edit):

		folder = self.view.window().folders()[0]
		os.chdir(folder)

		self.view.window().run_command("exec", {
			"cmd" : ["php artisan list"],
			"shell" : True,
			"working_dir" : folder}) 
Example 44
Project: SublimeText2-laravel5.2-artisan-cli   Author: Rotron   File: SublimeArtisan.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def run(self, edit):

		folder = self.view.window().folders()[0]
		os.chdir(folder)

		self.view.window().run_command("exec", {
			"cmd" : ["php artisan up"],
			"shell" : True,
			"working_dir" : folder}) 
Example 45
Project: SublimeText2-laravel5.2-artisan-cli   Author: Rotron   File: SublimeArtisan.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def run(self, edit):

		folder = self.view.window().folders()[0]
		os.chdir(folder)

		self.view.window().run_command("exec", {
			"cmd" : ["php artisan down"],
			"shell" : True,
			"working_dir" : folder}) 
Example 46
Project: SublimeText2-laravel5.2-artisan-cli   Author: Rotron   File: SublimeArtisan.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def run(self, edit):

		folder = self.view.window().folders()[0]
		os.chdir(folder)

		self.view.window().run_command("exec", {
			"cmd" : ["osascript -e 'tell application \"Terminal\" to do script \"php "+folder+"/artisan tinker\"'"],
			"shell" : True,
			"working_dir" : folder}) 
Example 47
Project: SublimeText2-laravel5.2-artisan-cli   Author: Rotron   File: SublimeArtisan.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def run(self, edit):

		folder = self.view.window().folders()[0]
		os.chdir(folder)

		self.view.window().run_command("exec", {
			"cmd" : ["php artisan env"],
			"shell" : True,
			"working_dir" : folder}) 
Example 48
Project: SublimeText2-laravel5.2-artisan-cli   Author: Rotron   File: SublimeArtisan.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def run(self, edit):

		folder = self.view.window().folders()[0]
		os.chdir(folder)

		self.view.window().run_command("exec", {
			"cmd" : ["php artisan"],
			"shell" : True,
			"working_dir" : folder}) 
Example 49
Project: SublimeText2-laravel5.2-artisan-cli   Author: Rotron   File: SublimeArtisan.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def on_done(self, generate_command):
		try:
			folder = self.window.folders()[0]
			os.chdir(folder)
			args = generate_command.split(" ")
			cmd = args[0]
			print ([cmd, args[0:]])		
			self.window.run_command("exec", {
				"cmd" : ["php /usr/local/bin/composer create-project --prefer-dist laravel/laravel " + cmd],
				"shell" : True,
				"working_dir" : folder})
		except ValueError:
			pass 
Example 50
Project: SublimeText2-laravel5.2-artisan-cli   Author: Rotron   File: SublimeArtisan.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def on_done(self, generate_command):
		try:
			folder = self.window.folders()[0]
			os.chdir(folder)
			args = generate_command.split(" ")
			cmd = args[0]
			print (["php", "artisan", cmd, args[0:]])
			self.window.run_command("exec", {
				"cmd" : ["php artisan app:name " + cmd],
				"shell" : True,
				"working_dir" : folder})
		except ValueError:
			pass