从 python 和 return 变量调用 bash 脚本
Call bash script from python and return variable
我正在尝试 运行 Python 中的以下代码,它调用 Bash 脚本文件并将其输出保存到一个变量。我正在尝试使用 subprocess.check_output
,但它引发了 "No such file or directory" 的错误。 subprocess.call
也不行。这是我的一些代码。
answer = subprocess.check_output(['/directory/bashfile.bash -c /directory/file -i input -o output'])
print answer
-c
-i
和 -o
只是脚本的参数 bashfile
.
问题是您传递的是整个命令字符串,而不是将它们拆分为参数。您要么需要将其作为 shell 命令传递:
answer = subprocess.check_output('/directory/bashfile.bash -c /directory/file -i input -o output',
shell=True)
print answer
或者你需要自己分词:
answer = subprocess.check_output(['/directory/bashfile.bash',
'-c', '/directory/file',
'-i', 'input',
'-o', 'output'])
print answer
有关子流程的更多信息,请参阅 the docs (python 3 version here)! Specifically you will want to read the section about "Frequently used arguments"
我正在尝试 运行 Python 中的以下代码,它调用 Bash 脚本文件并将其输出保存到一个变量。我正在尝试使用 subprocess.check_output
,但它引发了 "No such file or directory" 的错误。 subprocess.call
也不行。这是我的一些代码。
answer = subprocess.check_output(['/directory/bashfile.bash -c /directory/file -i input -o output'])
print answer
-c
-i
和 -o
只是脚本的参数 bashfile
.
问题是您传递的是整个命令字符串,而不是将它们拆分为参数。您要么需要将其作为 shell 命令传递:
answer = subprocess.check_output('/directory/bashfile.bash -c /directory/file -i input -o output',
shell=True)
print answer
或者你需要自己分词:
answer = subprocess.check_output(['/directory/bashfile.bash',
'-c', '/directory/file',
'-i', 'input',
'-o', 'output'])
print answer
有关子流程的更多信息,请参阅 the docs (python 3 version here)! Specifically you will want to read the section about "Frequently used arguments"