python - 如何通过子进程将带有空格的参数传递给 bash?

标签 python shell subprocess

我有一个调用另一个 shell 脚本的 Python 脚本 -

arg1 = "-a"
arg2 = "-b"
arg3 = "Some String"

argList = ["script.sh", arg1, arg2, arg3]
subprocess.call(argList)

当我运行脚本时,arg3 被拆分为 "Some""String" 并作为两个单独的参数传递。

如何克服这个问题,将 "Some String" 作为单个参数传递?

编辑:已解决

我通过将参数作为 $1、$2、$3、.. 等在被调用脚本内部调用另一个函数。当我应该引用可能包含 $1、$2、"$3"等空格的参数时......等等。抱歉造成混淆。

最佳答案

这应该有效:

import subprocess

arg1 = "-a"
arg2 = "-b"
arg3 = "Some String"

argList = ["sh", "script.sh", arg1, arg2, arg3]

subprocess.call(argList)

script.sh

里面
printf '%s\n' "$@"

确保 "$@" 被引用以避免在您的 shell 脚本中分词。

这将输出:

-a
-b
Some String

关于python - 如何通过子进程将带有空格的参数传递给 bash?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48276203/

相关文章:

python - 进程终止后Popen对象的returncode为None

linux - 为什么在 bash 脚本中查找匹配的 `"' 错误时会出现语法错误和意外的 EOF?

C 程序 - 我无法在后台运行 shell 脚本

python - 使用 sudo 在 python 中运行 Linux 子进程

python - 如何从基于行的字典列表创建 Pandas DataFrame

swift - 如何运行 shell 命令并让它在命令运行时打印输出?

python - 如何异步获取子进程的标准输出数据?

Python Mechanize - 如何在单个 .open() 调用上添加 header ?

python - 关于 sympy.printing.mathml 中的括号错误

python - TypeError : coercing to Unicode: need string or buffer, list found