【问题标题】:pass parameter into subprocess.Popen arguments将参数传递给 subprocess.Popen 参数
【发布时间】:2014-08-20 06:54:38
【问题描述】:

我是 Python 新手,需要编写一个脚本。

我有一个参数 result,我需要将它传递给 subprocess.Popen 中的参数

试图这样做

proc = subprocess.Popen(['sed', '-i', '/x/c\y = 'result'', 
                         '/home/test/1.txt'], stdout=subprocess.PIPE) 

但它给出了语法错误。如果我这样走:

proc = subprocess.Popen(['sed', '-i', '/x/c\y = ', result, 
                         '/home/test/1.txt'], stdout=subprocess.PIPE)

sed 错误实现了结果,不像/x/c\y = 的结尾,而是像一个单独的值

【问题讨论】:

    标签: python bash subprocess popen


    【解决方案1】:

    您必须使用 + 运算符连接字符串

    proc = subprocess.Popen(['sed', '-i', '/x/c\y = 'result'', ...\
                                                    ^      ^
    

    proc = subprocess.Popen(['sed', '-i', '/x/c\y = '+result+'', ...\
    

    【讨论】:

      【解决方案2】:
      proc = subprocess.Popen("sed -i /x/c\y = "+result+" /home/test/1.txt",shell=True,stdout=subprocess.PIPE)
      

      如果您从默认位置使用 sed,也可以尝试使用 shell=True 选项。

      【讨论】:

        猜你喜欢
        • 2014-02-13
        • 2016-09-08
        • 2017-02-18
        • 1970-01-01
        • 2019-09-27
        • 2010-09-14
        相关资源
        最近更新 更多