我正在尝试将参数从 python 传递给 bash 脚本。官方文档说需要用逗号分隔,但我正在使用它,但它不起作用。
subprocess.run(["/bin/bash test.sh", "hello", "dog", "3" ], shell=True)
在 bash 脚本中,我有以下基本代码:
echo "The number of arguments is: $#"
结果是:参数数量是:0
有什么建议吗?我决定将其作为字符串传递(不太干净),放置一个空格“”+“hello”+“dog”+“3”
问候,
最佳答案
您有两个选择。
使用参数列表调用它,但不使用
shell=True
:subprocess.run(["/bin/bash", "test.sh", "hello", "dog", "3" ])
使用
shell=True
传递单个字符串:subprocess.run("/bin/bash test.sh hello dog 3", shell=True)
On POSIX with
shell=True
, the shell defaults to/bin/sh
. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.
有关 shell
标志的更多信息:Actual meaning of 'shell=True' in subprocess
关于python - 使用子进程将参数传递给 bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60591358/