将bash脚本中的文件转储到运行python脚本的不同目录中
我有一个包含以下代码的python脚本将bash脚本中的文件转储到运行python脚本的不同目录中,python,shell,subprocess,Python,Shell,Subprocess,我有一个包含以下代码的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([cdwri
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/
中的所有文件。。。
我的意思是这是有道理的,但我不确定“ego”应该假设什么-我的python代码看到的或shell脚本看到的,我认为它在shell中运行,所以如果我在shell中cd,它将cd到所需的目录并在那里转储输出?您应该在同一命令中更改目录:
cmd = "/path/to/executable/executable"
outputdir = "/path/to/output/"
subprocess.call("cd {} && {}".format(outputdir, cmd), shell=True)
发生的情况是,这两个命令是独立执行的。您要做的是将cd放入目录中,然后执行
subprocess.call(';'.join([cdwrite, exec]), shell=True)
您是否在与python文件相同的目录中运行脚本?根据您现在所拥有的,这些文件应该输出到运行python脚本的目录(该目录可能是也可能不是包含脚本的目录)。这也意味着,如果您提供的路径是相对的,那么它将相对于运行python脚本的目录。您可以使用
cwd
参数:
from subprocess import check_call
cmd = "/path/to/executable/executable"
check_call([cmd], cwd="/path/to/output")
注意:不要不必要地使用shell=True