将bash脚本中的文件转储到运行python脚本的不同目录中

2024-07-02 13:57:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有以下代码的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/中的所有文件。。。 我的意思是这是有道理的,但是我不确定“ego”应该假设什么-我的python代码看到的或者shell脚本看到的,我认为它在shell中运行,所以如果我在shell中cd,它会cd到所需的目录并将输出转储到那里?你知道吗


Tags: topath代码脚本trueoutputscriptcd
3条回答

所发生的是这两个命令是独立执行的。您要做的是将cd放入目录,然后执行。你知道吗

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

您是否在与python文件相同的目录中运行脚本?根据现在的情况,文件应该输出到运行python脚本的目录(该目录可能是或不是包含脚本的目录)。这也意味着如果您给出的路径cd是相对的,那么它将是相对于您运行python脚本的目录的。你知道吗

可以使用cwd参数:

from subprocess import check_call

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

注意:不要不必要地使用shell=True。你知道吗

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

cmd = "/path/to/executable/executable"
outputdir = "/path/to/output/"
subprocess.call("cd {} && {}".format(outputdir, cmd), shell=True)

相关问题 更多 >