Python: Is it possible to change the Windows command line shell current directory without changing the actual current directory?

半腔热情 提交于 2019-12-04 07:13:13

The subprocess module is intended to replace os.system.

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).

See: http://docs.python.org/library/subprocess.html

Example usage replacing os.system:

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

If it only has to work on Windows, one way might be:

os.system('start /d newPath cmd')

When you use os.system, you're not reusing the same command shell, but spawning a new one for each request. This means that you can't actually expect changes in it to propagate between invocations.

You could write a wrapper though, that will always change to the directory you want before launching the command.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!