Python:是否可以更改Windows命令行shell当前目录,而不更改实际的当前目录? [英] Python: Is it possible to change the Windows command line shell current directory without changing the actual current directory?

查看:213
本文介绍了Python:是否可以更改Windows命令行shell当前目录,而不更改实际的当前目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 os.system()执行Windows命令行shell执行。我想更改Windows cmd的当前目录。这里有一种方法:

I'm using os.system() to do Windows command line shell executions. I would like to change the Windows cmd current directory. Here's one way of doing it:

os.chdir('newPath')

但是 chdir()也会更改实际的Python当前工作目录。我不想改变实际的Python工作目录,因为我想让我的脚本的其他部分在原来的当前工作目录中运行。我想要更改的只是Windows cmd当前工作目录。换句话说:我想要 os.system()命令在一个当前工作目录(Windows cmd当前工作目录)中运行,而其他任何应该运行在另一个当前工作目录

But chdir() will also change the actual Python current working directory. I don't want to change the actual Python working directory because I want other parts of my script to run in the original current working directory. What I want to change is only the Windows cmd current working directory. In other words: I want os.system() commands to run in one current working directory (Windows cmd current working directory) while anything else should run in another current working directory (the actual Python current working directory).

这里是另一个尝试更改 Windows cmd目录:

Here's another try to change only the Windows cmd current directory:

os.system('cd newPath')


$ b b

然而,这显然不工作,因为在执行 cd newPath 命令后,Windows cmd当前目录被重置(因为我不会使用在下一次调用 os.system()时使用相同的Windows命令shell。

However, that obviously doesn't work since right after the execution of the cd newPath command the Windows cmd current directory is reset (because I won't use the same Windows command shell in the next call to os.system()).

单独的当前工作目录为Windows cmd shell? (与实际当前工作目录分开)。

Is it possible to have a separate current working directory for the Windows cmd shell? (separate from the actual current working directory).

推荐答案

subprocess 模块旨在替换 os.system

其他方面,它给你 subprocess.Popen(),它需要一个

Among other things, it gives you subprocess.Popen(), which takes a cwd argument to specify the working directory for the spawned process (for exactly your situation).

请参阅:参数指定生成的进程的工作目录/docs.python.org/library/subprocess.html\">http://docs.python.org/library/subprocess.html

使用范例替换 os.system

p = subprocess.Popen("yourcmd" + " yourarg", shell=True, cwd="c:/your/path")
sts = os.waitpid(p.pid, 0)[1]

这篇关于Python:是否可以更改Windows命令行shell当前目录,而不更改实际的当前目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆