Python os.chdir() Examples

The following are 30 code examples of os.chdir(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: get_data.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 10 votes vote down vote up
def get_cifar10(data_dir):
    if not os.path.isdir(data_dir):
        os.system("mkdir " + data_dir)
    cwd = os.path.abspath(os.getcwd())
    os.chdir(data_dir)
    if (not os.path.exists('train.rec')) or \
       (not os.path.exists('test.rec')) :
        import urllib, zipfile, glob
        dirname = os.getcwd()
        zippath = os.path.join(dirname, "cifar10.zip")
        urllib.urlretrieve("http://data.mxnet.io/mxnet/data/cifar10.zip", zippath)
        zf = zipfile.ZipFile(zippath, "r")
        zf.extractall()
        zf.close()
        os.remove(zippath)
        for f in glob.glob(os.path.join(dirname, "cifar", "*")):
            name = f.split(os.path.sep)[-1]
            os.rename(f, os.path.join(dirname, name))
        os.rmdir(os.path.join(dirname, "cifar"))
    os.chdir(cwd)

# data 
Example #2
Source File: test_values.py    From python-template with Apache License 2.0 7 votes vote down vote up
def test_dash_in_project_slug(cookies):
    ctx = {'project_slug': "my-package"}
    project = cookies.bake(extra_context=ctx)

    assert project.exit_code == 0

    with open(os.path.join(str(project.project), 'setup.py')) as f:
        setup = f.read()
    print(setup)

    cwd = os.getcwd()
    os.chdir(str(project.project))

    try:
        sh.python(['setup.py', 'install'])
        sh.python(['setup.py', 'build_sphinx'])
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
    finally:
        os.chdir(cwd) 
Example #3
Source File: test_values.py    From python-template with Apache License 2.0 7 votes vote down vote up
def test_double_quotes_in_name_and_description(cookies):
    ctx = {'project_short_description': '"double quotes"',
           'full_name': '"name"name'}
    project = cookies.bake(extra_context=ctx)

    assert project.exit_code == 0

    with open(os.path.join(str(project.project), 'setup.py')) as f:
        setup = f.read()
    print(setup)

    cwd = os.getcwd()
    os.chdir(str(project.project))

    try:
        sh.python(['setup.py', 'install'])
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
    finally:
        os.chdir(cwd) 
Example #4
Source File: payday.py    From payday with GNU General Public License v2.0 6 votes vote down vote up
def get_payload_output(payload_output_dir):
	""" Builds directory structure if output option is supplied """
	output_dir = payload_output_dir
	# check to see if the trailing slash has been added to the path : ie /root/path
	if not output_dir.endswith("/"):
		output_dir = output_dir + "/"

	# creates the structure if it doesn't exist
	if not os.path.isdir(output_dir):
		print(yellowtxt("[!] Creating output directory structure"))
		os.mkdir(output_dir)
		os.chdir(output_dir)
		os.mkdir('handlers')
	return output_dir



###############################
### 	Helper Function	    ###
############################### 
Example #5
Source File: _qemu.py    From ALF with Apache License 2.0 6 votes vote down vote up
def _remote_init(working_dir):
    global pickle
    import pickle
    import sys
    import shutil
    import os
    if not os.path.isdir(working_dir):
        os.mkdir(working_dir)
    sys.path.append(working_dir)
    shutil.move("_common.py", working_dir)
    shutil.move("_gdb.py", working_dir)
    shutil.move("cmds.gdb", working_dir)
    # setup CERT exploitable
    exp_lib_dir = os.path.join(working_dir, "exploitable", "lib")
    os.makedirs(exp_lib_dir)
    shutil.move("exploitable.py", os.path.join(working_dir, "exploitable"))
    shutil.move("__init__.py", exp_lib_dir)
    shutil.move("analyzers.py", exp_lib_dir)
    shutil.move("classifier.py", exp_lib_dir)
    shutil.move("elf.py", exp_lib_dir)
    shutil.move("gdb_wrapper.py", exp_lib_dir)
    shutil.move("rules.py", exp_lib_dir)
    shutil.move("tools.py", exp_lib_dir)
    shutil.move("versions.py", exp_lib_dir)
    os.chdir(working_dir)
    global _common
    global _gdb
    import _common
    import _gdb 
Example #6
Source File: batch.py    From aegea with Apache License 2.0 6 votes vote down vote up
def ensure_lambda_helper():
    awslambda = getattr(clients, "lambda")
    try:
        helper_desc = awslambda.get_function(FunctionName="aegea-dev-process_batch_event")
        logger.info("Using Batch helper Lambda %s", helper_desc["Configuration"]["FunctionArn"])
    except awslambda.exceptions.ResourceNotFoundException:
        logger.info("Batch helper Lambda not found, installing")
        import chalice.cli
        orig_argv = sys.argv
        orig_wd = os.getcwd()
        try:
            os.chdir(os.path.join(os.path.dirname(__file__), "batch_events_lambda"))
            sys.argv = ["chalice", "deploy", "--no-autogen-policy"]
            chalice.cli.main()
        except SystemExit:
            pass
        finally:
            os.chdir(orig_wd)
            sys.argv = orig_argv 
Example #7
Source File: test_runtime.py    From calmjs with GNU General Public License v2.0 6 votes vote down vote up
def test_calmjs_main_console_entry_point_install(self):
        remember_cwd(self)
        tmpdir = mkdtemp(self)
        os.chdir(tmpdir)
        stub_stdouts(self)
        stub_mod_call(self, cli, fake_error(IOError))

        with self.assertRaises(SystemExit) as e:
            runtime.main(['npm', '--init', 'calmjs'])
        # this should be fine, exit code 0
        self.assertEqual(e.exception.args[0], 0)

        with self.assertRaises(SystemExit) as e:
            runtime.main(['npm', '--install', 'calmjs'])
        self.assertIn(
            "invocation of the 'npm' binary failed;", sys.stderr.getvalue())
        self.assertEqual(e.exception.args[0], 1) 
Example #8
Source File: defaultvalues.py    From CAMISIM with Apache License 2.0 6 votes vote down vote up
def __init__(self, label="DefaultValues", logfile=None, verbose=False, debug=False):
        super(DefaultValues, self).__init__(label=label, logfile=logfile, verbose=verbose, debug=debug)
        self._validator = Validator(logfile=logfile, verbose=verbose, debug=debug)
        pipeline_dir = os.path.dirname(self._validator.get_full_path(os.path.dirname(scripts.__file__)))

        self._DEFAULT_seed = random.randint(0, 2147483640)
        self._DEFAULT_tmp_dir = tempfile.gettempdir()
        self._DEFAULT_directory_pipeline = pipeline_dir

        original_wd = os.getcwd()
        os.chdir(pipeline_dir)
        file_path_config = os.path.join(pipeline_dir, "default_config.ini")
        if self._validator.validate_file(file_path_config, silent=True):
            self._from_config(file_path_config)
        else:
            self._from_hardcoded(pipeline_dir)
        os.chdir(original_wd) 
Example #9
Source File: test_runtime.py    From calmjs with GNU General Public License v2.0 6 votes vote down vote up
def test_npm_binary_not_found_debugger_disabled(self):
        remember_cwd(self)
        tmpdir = mkdtemp(self)
        os.chdir(tmpdir)
        rt = self.setup_runtime()
        # stub_stdin(self, u'quit\n')
        stub_stdouts(self)

        # ensure the binary is not found.
        stub_mod_call(self, cli, fake_error(IOError))
        rt(['-dd', 'foo', '--install', 'example.package2'])

        stderr = sys.stderr.getvalue()
        self.assertIn("ERROR", stderr)
        self.assertIn(
            "invocation of the 'npm' binary failed;", stderr)
        self.assertIn("terminating due to unexpected error", stderr)
        self.assertIn("Traceback ", stderr)
        # Note that since 3.4.0, post_mortem must be explicitly enabled
        # for the runtime class/instance
        self.assertNotIn("(Pdb)", sys.stdout.getvalue())
        self.assertIn(
            "instances of 'calmjs.runtime.Runtime' has disabled post_mortem "
            "debugger", sys.stderr.getvalue()
        ) 
Example #10
Source File: node.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def install_chute(ctx, directory):
    """
    Install a chute from the working directory.

    Install the files in the current directory as a chute on the node.
    The directory must contain a paradrop.yaml file.  The entire directory
    will be copied to the node for installation.
    """
    os.chdir(directory)

    if not os.path.exists("paradrop.yaml"):
        raise Exception("No paradrop.yaml file found in chute directory.")

    client = ctx.obj['client']
    with tempfile.TemporaryFile() as temp:
        tar = tarfile.open(fileobj=temp, mode="w")
        for dirName, subdirList, fileList in os.walk("."):
            for fname in fileList:
                path = os.path.join(dirName, fname)
                arcname = os.path.normpath(path)
                tar.add(path, arcname=arcname)
        tar.close()

        temp.seek(0)
        result = client.install_tar(temp)
        ctx.invoke(watch_change_logs, change_id=result['change_id']) 
Example #11
Source File: server.py    From The-chat-room with MIT License 6 votes vote down vote up
def cd(self, message, conn):
        message = message.split()[1]                          # 截取目录名
        # 如果是新连接或者下载上传文件后的发送则 不切换 只将当前工作目录发送过去
        if message != 'same':
            f = r'./' + message
            os.chdir(f)
        # path = ''
        path = os.getcwd().split('\\')                        # 当前工作目录
        for i in range(len(path)):
            if path[i] == 'resources':
                break
        pat = ''
        for j in range(i, len(path)):
            pat = pat + path[j] + ' '
        pat = '\\'.join(pat.split())
        # 如果切换目录超出范围则退回切换前目录
        if 'resources' not in path:
            f = r'./resources'
            os.chdir(f)
            pat = 'resources'
        conn.send(pat.encode())

    # 判断输入的命令并执行对应的函数 
Example #12
Source File: test_runtime.py    From calmjs with GNU General Public License v2.0 6 votes vote down vote up
def test_npm_all_the_actions(self):
        remember_cwd(self)
        tmpdir = mkdtemp(self)
        os.chdir(tmpdir)
        stub_stdouts(self)
        stub_mod_call(self, cli)
        stub_base_which(self, which_npm)
        rt = self.setup_runtime()
        rt(['foo', '--install', '--view', '--init',
            'example.package1', 'example.package2'])

        # inside stdout
        result = json.loads(sys.stdout.getvalue())
        self.assertEqual(result['dependencies']['jquery'], '~3.1.0')
        self.assertEqual(result['dependencies']['underscore'], '~1.8.3')

        with open(join(tmpdir, 'package.json')) as fd:
            result = json.load(fd)

        self.assertEqual(result['dependencies']['jquery'], '~3.1.0')
        self.assertEqual(result['dependencies']['underscore'], '~1.8.3')
        # not foo install, but npm install since entry point specified
        # the actual runtime instance.
        self.assertEqual(self.call_args[0], ([which_npm, 'install'],)) 
Example #13
Source File: node.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def update_chute(ctx, directory):
    """
    Install a new version of the chute from the working directory.

    Install the files in the current directory as a chute on the node.
    The directory must contain a paradrop.yaml file.  The entire directory
    will be copied to the node for installation.
    """
    os.chdir(directory)

    if not os.path.exists("paradrop.yaml"):
        raise Exception("No paradrop.yaml file found in chute directory.")

    with open('paradrop.yaml', 'r') as source:
        config = yaml.safe_load(source)

    if 'name' not in config:
        click.echo('Chute name is not defined in paradrop.yaml.')
        return

    client = ctx.obj['client']
    with tempfile.TemporaryFile() as temp:
        tar = tarfile.open(fileobj=temp, mode="w")
        for dirName, subdirList, fileList in os.walk("."):
            for fname in fileList:
                path = os.path.join(dirName, fname)
                arcname = os.path.normpath(path)
                tar.add(path, arcname=arcname)
        tar.close()

        temp.seek(0)
        result = client.install_tar(temp, name=config['name'])
        ctx.invoke(watch_change_logs, change_id=result['change_id']) 
Example #14
Source File: get_data.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def get_mnist(data_dir):
    if not os.path.isdir(data_dir):
        os.system("mkdir " + data_dir)
    os.chdir(data_dir)
    if (not os.path.exists('train-images-idx3-ubyte')) or \
       (not os.path.exists('train-labels-idx1-ubyte')) or \
       (not os.path.exists('t10k-images-idx3-ubyte')) or \
       (not os.path.exists('t10k-labels-idx1-ubyte')):
        import urllib, zipfile
        zippath = os.path.join(os.getcwd(), "mnist.zip")
        urllib.urlretrieve("http://data.mxnet.io/mxnet/data/mnist.zip", zippath)
        zf = zipfile.ZipFile(zippath, "r")
        zf.extractall()
        zf.close()
        os.remove(zippath)
    os.chdir("..") 
Example #15
Source File: test_project.py    From python-template with Apache License 2.0 6 votes vote down vote up
def test_building_documentation_apidocs(cookies):
    project = cookies.bake(extra_context={'apidoc': 'yes'})

    assert project.exit_code == 0
    assert project.exception is None

    cwd = os.getcwd()
    os.chdir(str(project.project))

    try:
        sh.python(['setup.py', 'build_sphinx'])
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
    finally:
        os.chdir(cwd)

    apidocs = project.project.join('docs', '_build', 'html', 'apidocs')

    assert apidocs.join('my_python_project.html').isfile()
    assert apidocs.join('my_python_project.my_python_project.html').isfile() 
Example #16
Source File: test_project.py    From python-template with Apache License 2.0 6 votes vote down vote up
def test_install(cookies):
    project = cookies.bake()

    assert project.exit_code == 0
    assert project.exception is None

    cwd = os.getcwd()
    os.chdir(str(project.project))

    try:
        sh.python(['setup.py', 'install'])
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
    finally:
        os.chdir(cwd) 
Example #17
Source File: test_values.py    From python-template with Apache License 2.0 6 votes vote down vote up
def test_space_in_project_slug(cookies):
    ctx = {'project_slug': "my package"}
    project = cookies.bake(extra_context=ctx)

    assert project.exit_code == 0

    with open(os.path.join(str(project.project), 'setup.py')) as f:
        setup = f.read()
    print(setup)

    cwd = os.getcwd()
    os.chdir(str(project.project))

    try:
        sh.python(['setup.py', 'install'])
        sh.python(['setup.py', 'build_sphinx'])
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
    finally:
        os.chdir(cwd) 
Example #18
Source File: test_values.py    From python-template with Apache License 2.0 6 votes vote down vote up
def test_single_quotes_in_name_and_description(cookies):
    ctx = {'project_short_description': "'single quotes'",
           'full_name': "Mr. O'Keeffe"}
    project = cookies.bake(extra_context=ctx)

    assert project.exit_code == 0

    with open(os.path.join(str(project.project), 'setup.py')) as f:
        setup = f.read()
    print(setup)

    cwd = os.getcwd()
    os.chdir(str(project.project))

    try:
        sh.python(['setup.py', 'install'])
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
    finally:
        os.chdir(cwd) 
Example #19
Source File: test_docker_cache.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        logging.getLogger().setLevel(logging.DEBUG)

        # We need to be in the same directory than the script so the commands in the dockerfiles work as
        # expected. But the script can be invoked from a different path
        base = os.path.split(os.path.realpath(__file__))[0]
        os.chdir(base)

        docker_cache._login_dockerhub = MagicMock()  # Override login

        # Stop in case previous execution was dirty
        try:
            self._stop_local_docker_registry()
        except Exception:
            pass

        # Start up docker registry
        self._start_local_docker_registry() 
Example #20
Source File: plugin-manager.py    From docker-taiga with GNU General Public License v3.0 6 votes vote down vote up
def install(self):
        """
        Command: Iterate over all AVAILABLE plugins and pre-install them. They can be enabled later.
        :return:
        """

        print(' >> Installing plugins...')
        print(list(self._plugins.items()))

        for plugin_name, module in self._plugins.items():
            print(' >> Instaling plugin "%s"' % plugin_name)

            os.chdir(self._front_path)
            print('   .. installing frontend')
            module.frontend_setup()

            os.chdir('/usr/src/taiga-back/')
            print('   .. installing backend')
            module.backend_setup() 
Example #21
Source File: test_runtime.py    From calmjs with GNU General Public License v2.0 6 votes vote down vote up
def test_npm_install_integration(self):
        remember_cwd(self)
        tmpdir = mkdtemp(self)
        os.chdir(tmpdir)
        stub_mod_call(self, cli)
        stub_base_which(self, which_npm)
        rt = self.setup_runtime()
        rt(['foo', '--install', 'example.package1', 'example.package2'])

        with open(join(tmpdir, 'package.json')) as fd:
            result = json.load(fd)

        self.assertEqual(result['dependencies']['jquery'], '~3.1.0')
        self.assertEqual(result['dependencies']['underscore'], '~1.8.3')
        # not foo install, but npm install since entry point specified
        # the actual runtime instance.
        self.assertEqual(self.call_args[0], ([which_npm, 'install'],)) 
Example #22
Source File: data_helpers.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 5 votes vote down vote up
def get_chinese_text():
    if not os.path.isdir("data/"):
        os.system("mkdir data/")
    if (not os.path.exists('data/pos.txt')) or \
       (not os.path.exists('data/neg')):
        os.system("wget -q https://raw.githubusercontent.com/dmlc/web-data/master/mxnet/example/chinese_text.zip -P data/")
        os.chdir("./data")
        os.system("unzip -u chinese_text.zip")
        os.chdir("..") 
Example #23
Source File: profiler_executor.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 5 votes vote down vote up
def _download(data_dir):
    if not os.path.isdir(data_dir):
        os.system("mkdir " + data_dir)
    os.chdir(data_dir)
    if (not os.path.exists('train-images-idx3-ubyte')) or \
       (not os.path.exists('train-labels-idx1-ubyte')) or \
       (not os.path.exists('t10k-images-idx3-ubyte')) or \
       (not os.path.exists('t10k-labels-idx1-ubyte')):
        os.system("wget http://webdocs.cs.ualberta.ca/~bx3/data/mnist.zip")
        os.system("unzip -u mnist.zip; rm mnist.zip")
    os.chdir("..") 
Example #24
Source File: test_runtime.py    From calmjs with GNU General Public License v2.0 5 votes vote down vote up
def test_npm_binary_not_found_debugger_enabled(self):
        from calmjs import utils

        def fake_post_mortem(*a, **kw):
            sys.stdout.write('(Pdb) ')

        remember_cwd(self)
        tmpdir = mkdtemp(self)
        os.chdir(tmpdir)
        # use the CalmJSRuntime which has the post_mortem debugger
        # enabled.
        rt = self.setup_runtime(runtime.CalmJSRuntime)
        stub_stdouts(self)

        # ensure the binary is not found.
        stub_mod_call(self, cli, fake_error(IOError))
        # utils.post_mortem references pbd.post_mortem, stub that to
        # avoid triggering certain issues.
        stub_item_attr_value(self, utils, 'post_mortem', fake_post_mortem)
        rt(['-dd', 'foo', '--install', 'example.package2'])

        stderr = sys.stderr.getvalue()
        self.assertIn("ERROR", stderr)
        self.assertIn(
            "invocation of the 'npm' binary failed;", stderr)
        self.assertIn("terminating due to unexpected error", stderr)
        self.assertIn("Traceback ", stderr)
        self.assertIn("(Pdb)", sys.stdout.getvalue())

        stub_stdouts(self)
        self.assertNotIn("(Pdb)", stderr)
        rt(['foo', '--install', 'example.package2', '--debugger'])
        self.assertIn("(Pdb)", sys.stdout.getvalue()) 
Example #25
Source File: test_runtime.py    From calmjs with GNU General Public License v2.0 5 votes vote down vote up
def test_critical_log_exception(self):
        remember_cwd(self)
        tmpdir = mkdtemp(self)
        os.chdir(tmpdir)
        rt = self.setup_runtime()

        stub_stdouts(self)
        # ensure the binary is not found.
        stub_mod_call(self, cli, fake_error(RuntimeError('fake error')))
        rt(['foo', '--install', 'example.package2'])
        self.assertIn(
            "CRITICAL calmjs.runtime RuntimeError: fake error",
            sys.stderr.getvalue()) 
Example #26
Source File: build_windows.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 5 votes vote down vote up
def nix_build(args):
    path = args.output
    os.makedirs(path, exist_ok=True)
    with remember_cwd():
        os.chdir(path)
        logging.info("Generating project with CMake")
        check_call("cmake \
            -DUSE_CUDA=OFF \
            -DUSE_OPENCV=OFF \
            -DUSE_OPENMP=OFF \
            -DCMAKE_BUILD_TYPE=Debug \
            -GNinja ..", shell=True)
        check_call("ninja", shell=True) 
Example #27
Source File: util.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 5 votes vote down vote up
def remember_cwd():
    '''
    Restore current directory when exiting context
    '''
    curdir = os.getcwd()
    try: yield
    finally: os.chdir(curdir) 
Example #28
Source File: test_npm.py    From calmjs with GNU General Public License v2.0 5 votes vote down vote up
def test_npm_install_package_json(self):
        stub_mod_call(self, cli)
        stub_base_which(self, which_npm)
        tmpdir = mkdtemp(self)
        os.chdir(tmpdir)

        # This is faked.
        with pretty_logging(stream=StringIO()) as stderr:
            npm.npm_install()
            self.assertIn(
                "no package name supplied, "
                "not continuing with 'npm install'", stderr.getvalue())
        # However we make sure that it's been fake called
        self.assertIsNone(self.call_args)
        self.assertFalse(exists(join(tmpdir, 'package.json'))) 
Example #29
Source File: docker_cache.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 5 votes vote down vote up
def main() -> int:
    """
    Utility to create and publish the Docker cache to Docker Hub
    :return:
    """
    # We need to be in the same directory than the script so the commands in the dockerfiles work as
    # expected. But the script can be invoked from a different path
    base = os.path.split(os.path.realpath(__file__))[0]
    os.chdir(base)

    logging.getLogger().setLevel(logging.DEBUG)
    logging.getLogger('botocore').setLevel(logging.INFO)
    logging.getLogger('boto3').setLevel(logging.INFO)
    logging.getLogger('urllib3').setLevel(logging.INFO)
    logging.getLogger('s3transfer').setLevel(logging.INFO)

    def script_name() -> str:
        return os.path.split(sys.argv[0])[1]

    logging.basicConfig(format='{}: %(asctime)-15s %(message)s'.format(script_name()))

    parser = argparse.ArgumentParser(description="Utility for preserving and loading Docker cache", epilog="")
    parser.add_argument("--docker-registry",
                        help="Docker hub registry name",
                        type=str,
                        required=True)

    args = parser.parse_args()

    platforms = build_util.get_platforms()
    return build_save_containers(platforms=platforms, registry=args.docker_registry, load_cache=True) 
Example #30
Source File: util.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 5 votes vote down vote up
def chdir_to_script_directory():
    # We need to be in the same directory than the script so the commands in the dockerfiles work as
    # expected. But the script can be invoked from a different path
    base = os.path.split(os.path.realpath(__file__))[0]
    os.chdir(base)