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

寵の児 提交于 2019-12-21 16:49:03

问题


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

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

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

os.system('cd newPath')

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

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


回答1:


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]



回答2:


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

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



回答3:


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.



来源:https://stackoverflow.com/questions/4881312/python-is-it-possible-to-change-the-windows-command-line-shell-current-director

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