0

我有一个带有以下代码的 python 脚本。

Python script: /path/to/pythonfile/
Executable: /path/to/executable/
Desired Output Path: /path/to/output/

我的第一个猜测...

import subprocess

exec = "/path/to/executable/executable"
cdwrite = "cd /path/to/output/"

subprocess.call([cdwrite], shell=True)
subprocess.call([exec], shell=True)

这会将所有文件转储到/path/to/pythonfile/......我的意思是这是有道理的,但我不确定要假设什么“自我” - 我的 python 代码看到的或 shell 脚本的,我认为它shell中运行所以如果我在 shell 中 cd,它会 cd 到所需的目录并在那里转储输出?

4

3 回答 3

2

正在发生的事情是两个命令相互独立地执行。您要做的是 cd 进入目录,然后执行。

subprocess.call(';'.join([cdwrite, exec]), shell=True)

您是否在与 python 文件相同的目录中运行脚本?使用您现在拥有的文件,应该将文件输出到您运行 python 脚本的目录(可能是也可能不是脚本所在的目录)。这也意味着,如果您提供的路径cd是相对的,它将与您运行 python 脚本的目录相关。

于 2013-07-18T21:48:58.160 回答
0

您应该在同一命令中更改目录:

cmd = "/path/to/executable/executable"
outputdir = "/path/to/output/"
subprocess.call("cd {} && {}".format(outputdir, cmd), shell=True)
于 2013-07-18T21:48:15.550 回答
0

你可以使用cwd参数:

from subprocess import check_call

cmd = "/path/to/executable/executable"
check_call([cmd], cwd="/path/to/output")

注意:不要shell=True不必要地使用。

于 2013-07-18T21:53:00.660 回答