[英]Running script file through subprocess
I'm attempting to run a Linux script through Python's subprocess module.我正在尝试通过 Python 的子进程模块运行 Linux 脚本。 Below is the subprocess command:
下面是子进程命令:
result = subprocess.run(['/dir/scripts/0_texts.sh'], shell=True)
print(result)
Here is the 0_texts.sh
script file:这是
0_texts.sh
脚本文件:
cd /dir/TXTs
pylanguagetool text_0.txt > comments_0.txt
The subprocess command executes the script file, writing a new comments_0.txt
in the correct directory. subprocess 命令执行脚本文件,在正确的目录中写入一个新的
comments_0.txt
。 However, there's an error in the execution.但是,执行时出现错误。 The
comments_0.txt
contains an error of "input file is required", and the subprocess result returns returncode=2
. comments_0.txt
出现“input file is required”的错误,subprocess 结果返回returncode=2
。 When I run the pylanguagetool text_0.txt > comments_0.txt
directly in the terminal the command executes properly, with the comments_0.txt
written with the proper input file of text_0.txt
.当我直接在终端中运行
pylanguagetool text_0.txt > comments_0.txt
时,命令正确执行, comments_0.txt
使用正确的输入文件text_0.txt
。
Any suggestions on what I'm missing?对我所缺少的有什么建议吗?
There is some ambiguity here in that it's not obvious which shell is run each time 0_texts.sh
is invoked, and whether it has the values you expect of environment variables like PATH
, which could result in a different copy of pylanguagetool
running from when you call it at the command line.这里有一些歧义,因为每次调用
0_texts.sh
时运行哪个 shell 并不明显,以及它是否具有您期望的环境变量值,如PATH
,这可能会导致pylanguagetool
在您调用时运行不同的副本它在命令行。
First I'd suggest removing the shell=True
option in subprocess.run
, which is only involving another, potentially different shell here.首先,我建议删除 subprocess.run 中的
subprocess.run
shell=True
选项,它只涉及另一个可能不同的 shell 。 Next I would change subprocess.run(['/dir/scripts/0_texts.sh'])
to subprocess.run(['bash', '/dir/scripts/0_texts.sh'])
(or whichever shell you wanted to run, probably bash
or dash
) to remove that source of ambiguity.接下来,我会将
subprocess.run(['/dir/scripts/0_texts.sh'])
更改为 subprocess.run subprocess.run(['bash', '/dir/scripts/0_texts.sh'])
(或您想要的任何一个 shell运行,可能是bash
或dash
)以消除歧义源。 Finally, you can try using type pylanguagetool
in the script, invoking pylanguagetool
with its full path, or calling bash /dir/scripts/0_texts.sh
from your terminal to debug the situation further.最后,您可以尝试在脚本中使用
type pylanguagetool
,使用其完整路径调用pylanguagetool
,或从您的终端调用bash /dir/scripts/0_texts.sh
以进一步调试情况。
A bigger-picture issue is, pyLanguageTool is a Python library, so you're almost certainly going to be better off calling its functions from your original Python script directly instead of using a shell script as an intermediary.一个更大的问题是,pyLanguageTool 是一个 Python 库,因此您几乎可以肯定直接从原始 Python 脚本调用它的函数会更好,而不是使用 shell 脚本作为中介。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.