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 |
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 |
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 #3
Source File: test_values.py From python-template with Apache License 2.0 | 7 votes |
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 #4
Source File: batch.py From aegea with Apache License 2.0 | 6 votes |
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 #5
Source File: _qemu.py From ALF with Apache License 2.0 | 6 votes |
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: defaultvalues.py From CAMISIM with Apache License 2.0 | 6 votes |
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 #7
Source File: server.py From The-chat-room with MIT License | 6 votes |
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 #8
Source File: payday.py From payday with GNU General Public License v2.0 | 6 votes |
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 #9
Source File: test_values.py From python-template with Apache License 2.0 | 6 votes |
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 #10
Source File: test_values.py From python-template with Apache License 2.0 | 6 votes |
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 #11
Source File: test_project.py From python-template with Apache License 2.0 | 6 votes |
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 #12
Source File: test_project.py From python-template with Apache License 2.0 | 6 votes |
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 #13
Source File: get_data.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
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 #14
Source File: test_docker_cache.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
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 #15
Source File: plugin-manager.py From docker-taiga with GNU General Public License v3.0 | 6 votes |
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 #16
Source File: node.py From Paradrop with Apache License 2.0 | 6 votes |
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 #17
Source File: node.py From Paradrop with Apache License 2.0 | 6 votes |
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 #18
Source File: test_runtime.py From calmjs with GNU General Public License v2.0 | 6 votes |
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 #19
Source File: test_runtime.py From calmjs with GNU General Public License v2.0 | 6 votes |
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 #20
Source File: test_runtime.py From calmjs with GNU General Public License v2.0 | 6 votes |
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 #21
Source File: test_runtime.py From calmjs with GNU General Public License v2.0 | 6 votes |
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 #22
Source File: arm_now.py From arm_now with MIT License | 5 votes |
def do_offline(): URL = "https://github.com/nongiach/arm_now_templates/archive/master.zip" templates = str(Path.home()) + "/.config/arm_now/templates/" master_zip = str(Path.home()) + "/.config/arm_now/templates/master.zip" os.makedirs(templates) # download_from_github(arch) download(URL, master_zip, Config.DOWNLOAD_CACHE_DIR) os.chdir(templates) check_call("unzip master.zip", shell=True) check_call("mv arm_now_templates-master/* .", shell=True) check_call("rm -rf arm_now_templates-master/ README.md master.zip", shell=True)
Example #23
Source File: local.py From ALF with Apache License 2.0 | 5 votes |
def local_run(): opts, arg_error = parse_args() if opts.verbose: log.getLogger().setLevel(log.DEBUG) proj_cls = load_project(opts.project_name) if opts.reduce: for r in opts.reduce: if r not in reducers: arg_error("unknown reducer: \"%r\"" % r) tmp_wd = os.getcwd() if os.path.isdir(opts.template_or_directory): test_dir = os.path.abspath(opts.template_or_directory) tests = [os.path.join(test_dir, test) for test in os.listdir(opts.template_or_directory)] run_folder = "%s_%s_dir_replay" % (time.strftime("%Y%m%d-%H%M%S"), opts.project_name) else: tests = [opts.template_or_directory] run_folder = "%s_%s_local" % (time.strftime("%Y%m%d-%H%M%S"), opts.project_name) os.mkdir(run_folder) for template_fn in tests: template_fn = os.path.abspath(template_fn) os.chdir(run_folder) main(opts.project_name, proj_cls(template_fn), run_folder, template_fn, opts.iterations, opts.min_aggr, opts.max_aggr, opts.keep_mutations, opts.timeout, opts.pickle_result, opts.reduce, opts.reducen) os.chdir(tmp_wd)
Example #24
Source File: plugins.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _make_absolute(filename): """Ensure filename is absolute to avoid effect of os.chdir.""" return filename if os.path.isabs(filename) else ( os.path.normpath(os.path.join(_module__file__base, filename)) )
Example #25
Source File: wspbus.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _do_execv(self): """Re-execute the current process. This must be called from the main thread, because certain platforms (OS X) don't allow execv to be called in a child thread very well. """ try: args = self._get_true_argv() except NotImplementedError: """It's probably win32 or GAE""" args = [sys.executable] + self._get_interpreter_argv() + sys.argv self.log('Re-spawning %s' % ' '.join(args)) self._extend_pythonpath(os.environ) if sys.platform[:4] == 'java': from _systemrestart import SystemRestart raise SystemRestart else: if sys.platform == 'win32': args = ['"%s"' % arg for arg in args] os.chdir(_startup_cwd) if self.max_cloexec_files: self._set_cloexec() os.execv(sys.executable, args)
Example #26
Source File: server.py From The-chat-room with MIT License | 5 votes |
def __init__(self, port): threading.Thread.__init__(self) # self.setDaemon(True) self.ADDR = ('', port) # self.PORT = port os.chdir(sys.path[0]) self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # self.conn = None # self.addr = None # 用于接收所有客户端发送信息的函数
Example #27
Source File: server.py From The-chat-room with MIT License | 5 votes |
def __init__(self, port): threading.Thread.__init__(self) # self.setDaemon(True) self.ADDR = ('', port) # self.PORT = port self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.first = r'.\resources' os.chdir(self.first) # 把first设为当前工作路径 # self.conn = None
Example #28
Source File: server.py From The-chat-room with MIT License | 5 votes |
def __init__(self, port): threading.Thread.__init__(self) # self.setDaemon(True) self.ADDR = ('', port) # self.PORT = port self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # self.conn = None os.chdir(sys.path[0]) self.folder = '.\\Server_image_cache\\' # 图片的保存文件夹
Example #29
Source File: payday.py From payday with GNU General Public License v2.0 | 5 votes |
def veil_payloads(ip, output_dir, move_payloads, veil_path, payload_port): """ Takes local IP address as LHOST parm and builds Veil payloads""" # Veil doesn't have a custom output directory option and the default path gets pulled from the config file # hacky approach :: copy each generated payload and handler in to the custom output directory if it is supplied # start empty list to hold os.chdir(veil_path) payloads = [] # appends payloads with nested 3 value list for dynamic parm calling payloads.append(["10",payload_port, "v_revhttps"]) payloads.append(["5",payload_port,"v_revhttp"]) payloads.append(["7",payload_port,"v_revmet"]) payloads.append(["6",payload_port, "v_revhttp_srv"]) print("Creating Veil Goodness") for parms in payloads: lhost = ip payload = parms[0] lport = str(parms[1]) output = parms[2] command = ("./Veil.py -t Evasion -p " + payload + " -c LHOST=" + lhost + " LPORT=" + lport + " -o " + output + " --ip " + ip) os.system(command) time.sleep(2) # if using a custom output directory, veil doesn't have an option to specify the base directory as it gets this from the conf file # payload generated above has unique 'base' name - access the list and check the boolean flag that is pushed in # if this is true, move the file/handler into the custom output directory so that all payloads are in custom location if move_payloads == True: # move payload os.system("mv /root/payloads/windows/" + output + ".exe " + output_dir) os.system("mv /root/payloads/windows/" + output + ".dll " + output_dir) # move handler os.system("mv /root/payloads/windows/handlers/" + output + "_handler.rc " + output_dir + "handlers")
Example #30
Source File: test_data.py From mlearn with BSD 3-Clause "New" or "Revised" License | 5 votes |
def setUpClass(cls): cls.this_dir = os.path.dirname(os.path.abspath(__file__)) cls.test_dir = tempfile.mkdtemp() os.chdir(cls.test_dir)