【问题标题】:How do I pass parameters with whitespaces to bash through subprocess?如何通过子进程将带有空格的参数传递给bash?
【发布时间】:2018-06-24 20:44:03
【问题描述】:

我有一个调用另一个 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" ..等等。抱歉给您带来了困惑。

【问题讨论】:

  • 使用:argList = ["sh", "script.sh", arg1, arg2, arg3]
  • 尝试将“sh”作为第一个参数。还是一样的。

标签: python shell subprocess


【解决方案1】:

这应该可行:

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

【讨论】:

  • 这是我最初所做的。我得到的输出是-a -b Some String 每个都是一个单独的参数(4)。另外,我正在使用 ZSH,你认为这是造成这种情况的原因吗?编辑:删除 ZSH,问题仍然存在。
  • @entropy.maximum:你能在你打印参数的地方显示你的 shell 脚本吗?
  • 我正在使用 "printf '%s\n' "$@" 进行打印。另外我正在运行 MacOS High Sierra。
  • 已修复。我通过将参数传递为 $1、$2、$3、.. 等来在内部调用另一个函数。当我应该引用可能包含空格的参数时,如 $1、$2、"$3" .. 等。谢谢!
【解决方案2】:

转义双引号,

arg3 = "\"Some String\""

【讨论】:

  • 抱歉,我认为您没有理解这个问题。我想将字符串作为单个参数传递,bash 将其解释为两个参数。另外,我正在使用 ZSH,这是一个问题吗?编辑:删除 ZSH。问题仍然存在。
【解决方案3】:

试试这个:

import shlex, subprocess
args=shlex.split('script.sh -a -b "Some String"')
subprocess.Popen(args)

【讨论】:

    【解决方案4】:

    这更像是一个扩展评论而不是一个答案。

    您的代码在我的 Debian 9.3 中运行良好

    $ cat sc.sh
    #!/bin/sh
    # Above line is mandatory - otherwise python returns error of unkonwn format
    echo "arg1=$1"
    echo "arg2=$2"
    echo "arg3=$3"
    echo "arg4=$4"
    
    $ chmod +x sc.sh
    
    $ pwd
    /home/gv
    
    $ cat test.py
    import subprocess
    arg1 = "-a"
    arg2 = "-b"
    arg3 = "some string"
    
    arglist = ["/home/gv/sc.sh", arg1, arg2, arg3]
    subprocess.call(arglist)
    
    $ python test.py
    arg1=-a
    arg2=-b
    arg3=some string
    arg4=
    

    PS : 在我的系统中安装了 python 2.17.14 和 bash 4.4.12

    【讨论】:

    • 谢谢。这是我的错。固定的。我通过将参数传递为 $1、$2、$3、.. 等来在内部调用另一个函数。当我应该引用可能包含空格的参数时,如 $1、$2、"$3" .. 等。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 2015-01-09
    • 2018-09-17
    • 2020-03-16
    • 2018-05-06
    • 2015-10-21
    相关资源
    最近更新 更多