python - 使用子进程将参数传递给 bash 脚本

标签 python bash

我正在尝试将参数从 python 传递给 bash 脚本。官方文档说需要用逗号分隔,但我正在使用它,但它不起作用。

subprocess.run(["/bin/bash test.sh", "hello", "dog", "3" ], shell=True)

在 bash 脚本中,我有以下基本代码:

echo "The number of arguments is: $#"

结果是:参数数量是:0

有什么建议吗?我决定将其作为字符串传递(不太干净),放置一个空格“”+“hello”+“dog”+“3”

问候,

最佳答案

您有两个选择。

  1. 使用参数列表调用它,但不使用 shell=True:

    subprocess.run(["/bin/bash", "test.sh", "hello", "dog", "3" ])
    
  2. 使用 shell=True 传递单个字符串:

    subprocess.run("/bin/bash test.sh hello dog 3", shell=True)
    

来自docs of subprocess :

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/

相关文章:

linux - 如何让wget仅在文件完整时保存文件

linux - 我可以在同一行的 file.txt 上写吗

python - "conversion from method to Decimal is not supported django"错误

python - Pandas dataframe to dict,同时保留重复行

python - 正则表达式匹配最后的模式

linux - 如何从子进程读取 valgrind 返回值?

bash - 在 bash 脚本中使用 GNU 超时和 SSH -t 来防止挂起

python - Ansible Django 模块替代 Python 解释器

python - Python反转计数器: slice indicies error

python - 使用 SQL 提取唯一值