Command line execution in different folder

2019-01-25 01:17发布

I'm calling a command line program in python using the os.system(command) call.

How can I call this command passing a different folder for execution? There is a system call for this? Or I should save the current folder, and, after execution, change restore it.

2条回答
淡お忘
2楼-- · 2019-01-25 01:59

The subprocess module is a very good solution.

import subprocess
p = subprocess.Popen([command, argument1,...], cwd=working_directory)
p.wait()

It has also arguments for modifying environment variables, redirecting input/output to the calling program, etc.

查看更多
女痞
3楼-- · 2019-01-25 02:12

Try to os.chdir(path) before invoking the command.

From here:

os.chdir(path) Change the current working directory to path.

Availability: Unix, Windows

EDIT

This will change the current working dir, you can get the current working by:

os.getcwd()

If you want to save it and restore it later, if you need to do some work in the original working dir.

EDIT 2

In any case you should probably move to subprocess (doc) as suggested here. If you use subprocess's Popen you have the choice of providing cwd parameter to specify the working directory for the subprocess: read this.

subprocess.Popen(args, bufsize=0, executable=None, stdin=None,
stdout=None, stderr=None, preexec_fn=None, close_fds=False,
shell=False, cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0)

...

If cwd is not None, the child’s current directory will be changed to cwd before it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd.

查看更多
登录 后发表回答