Python os 模块,chdir() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.chdir()

项目:charm-plumgrid-gateway    作者:openstack    | 项目源码 | 文件源码
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)
项目:rpwng    作者:MrNbaYoh    | 项目源码 | 文件源码
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
项目:rpwng    作者:MrNbaYoh    | 项目源码 | 文件源码
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
项目:Adafruit_Python_PureIO    作者:adafruit    | 项目源码 | 文件源码
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)
项目:py_find_1st    作者:roebel    | 项目源码 | 文件源码
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)
项目:Adafruit_Python_PCA9685    作者:adafruit    | 项目源码 | 文件源码
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)
项目:Python    作者:Guzi219    | 项目源码 | 文件源码
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()
项目:Python    作者:Guzi219    | 项目源码 | 文件源码
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()
项目:ardy    作者:avara1986    | 项目源码 | 文件源码
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"]))
项目:NeoVintageous    作者:NeoVintageous    | 项目源码 | 文件源码
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
项目:Home-Assistant    作者:jmart518    | 项目源码 | 文件源码
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()
项目:charm-swift-proxy    作者:openstack    | 项目源码 | 文件源码
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)
项目:charm-swift-proxy    作者:openstack    | 项目源码 | 文件源码
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)
项目:acbs    作者:AOSC-Dev    | 项目源码 | 文件源码
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
项目:acbs    作者:AOSC-Dev    | 项目源码 | 文件源码
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
项目:acbs    作者:AOSC-Dev    | 项目源码 | 文件源码
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
项目:BackManager    作者:linuxyan    | 项目源码 | 文件源码
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)
项目:wiki-to-doc    作者:serra    | 项目源码 | 文件源码
def build_mkdocs(self):
        """
        Invokes MkDocs to build the static documentation and moves the folder
        into the project root folder.
        """
        # Setting the working directory
        os.chdir(MKDOCS_DIR)

        # Building the MkDocs project
        pipe = subprocess.PIPE
        mkdocs_process = subprocess.Popen(
            ["mkdocs", "build", "-q"], stdout=pipe, stderr=pipe)
        std_op, std_err_op = mkdocs_process.communicate()

        if std_err_op:
            raise Error("Could not build MkDocs !\n%s" %
                        std_err_op)
项目:cmake.nvim    作者:phillipbonhomme    | 项目源码 | 文件源码
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)))
项目:cmake.nvim    作者:phillipbonhomme    | 项目源码 | 文件源码
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"))
项目:cmake.nvim    作者:phillipbonhomme    | 项目源码 | 文件源码
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"))
项目:cmake.nvim    作者:phillipbonhomme    | 项目源码 | 文件源码
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))
项目:cmake.nvim    作者:phillipbonhomme    | 项目源码 | 文件源码
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)
项目:ovn-kubernetes-charm    作者:AakashKT    | 项目源码 | 文件源码
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');
项目:ovn-kubernetes-charm    作者:AakashKT    | 项目源码 | 文件源码
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');
项目:Adafruit_Python_ADS1x15    作者:adafruit    | 项目源码 | 文件源码
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)
项目:ccu_and_eccu_publish    作者:gaofubin    | 项目源码 | 文件源码
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)
项目:bob    作者:BobBuildTool    | 项目源码 | 文件源码
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" }
项目:bob    作者:BobBuildTool    | 项目源码 | 文件源码
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"}
项目:Adafruit_Python_MCP4725    作者:adafruit    | 项目源码 | 文件源码
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)
项目:QUANTAXIS    作者:yutiansut    | 项目源码 | 文件源码
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?????
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
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()
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
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()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
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))
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
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()
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
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)
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
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()
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
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)
项目:charm-plumgrid-gateway    作者:openstack    | 项目源码 | 文件源码
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)
项目:Stitch    作者:nathanlopez    | 项目源码 | 文件源码
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
项目:pyupdater-wx-demo    作者:wettenhj    | 项目源码 | 文件源码
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))
项目:SublimeText2-laravel5.2-artisan-cli    作者:Rotron    | 项目源码 | 文件源码
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})
项目:SublimeText2-laravel5.2-artisan-cli    作者:Rotron    | 项目源码 | 文件源码
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})
项目:SublimeText2-laravel5.2-artisan-cli    作者:Rotron    | 项目源码 | 文件源码
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})
项目:SublimeText2-laravel5.2-artisan-cli    作者:Rotron    | 项目源码 | 文件源码
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})
项目:SublimeText2-laravel5.2-artisan-cli    作者:Rotron    | 项目源码 | 文件源码
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})
项目:SublimeText2-laravel5.2-artisan-cli    作者:Rotron    | 项目源码 | 文件源码
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})
项目:SublimeText2-laravel5.2-artisan-cli    作者:Rotron    | 项目源码 | 文件源码
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})
项目:SublimeText2-laravel5.2-artisan-cli    作者:Rotron    | 项目源码 | 文件源码
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