【问题标题】:Popen not pulling in argumentPopen 不参与争论
【发布时间】:2014-03-05 21:00:59
【问题描述】:

我正在尝试运行脚本并返回标准输出(输出)。

调用脚本的代码是:

def read_wl_file(self, wl_file, script):
    p = subprocess.Popen([script, wl_file], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return p.stdout.read()

脚本在下面,唯一的 arg 是要处理的文件

#!/bin/bash

usage(){
    echo "Usage: $0 processes the thingy file."
    exit 1 # error
}

# no arg, error
is_file_exits(){
    local f="$1"
    [[ -f "$f" ]] && return 0 || return 1
}

# invoke  usage if filename not supplied
[[ $# -eq 0 ]] && usage

# Invoke is_file_exits
if ( is_file_exits "$1" )
then
    #parse file code here....

else
    echo "File not found"
fi

我可以毫无问题地从我的 shell 运行它,但不能在 python 脚本中运行,因为我的单元测试失败了。

def test_can_decypt(self):
    output = self.data.read_wl_file('/Users/Bryan/Desktop/data.csv', "./xxx/script.sh")
    print output
    assert "Usage: ./xxx/script.sh processes thingy file." not in output

结果:

Usage: ./xxx/script.sh processes thingy file.

 F.
    ======================================================================
    FAIL: test_can_work (tests.file_tests.TestProcess)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File ".....test.py", line 17, in test_can_work
        assert "Usage: ./xxx/script.sh processes the thingy file." not in output
    AssertionError

----------------------------------------------------------------------
Ran 2 tests in 0.006s

所以测试告诉我,当 Popen 运行时它没有传入 arg,所以用法是错误的输出(因此测试失败)。我在这一点上迷路了。代码看到脚本,打开它但没有传递任何参数?

【问题讨论】:

    标签: python bash popen


    【解决方案1】:

    通常,您应该或者传递一个列表,或者传递一个带有shell=True的字符串。两者都不是。

    在您的情况下,您似乎没有使用 shell,所以我将删除该关键字:

    p = subprocess.Popen([script, wl_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    

    【讨论】:

    • 就是这样,我不敢相信这是问题所在。谢谢。
    • 在我对这个问题的所有研究中,我从来没有看到不使用 shell arg 的理由,但我确信这在某处的文档中。再次感谢。
    • +1:一个列表参数 shell=True在一起几乎总是一个错误。
    • @J.F.Sebastian -- 是的。感谢您在另一个问题上给我打电话(现已删除)
    猜你喜欢
    • 2011-12-15
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 2015-03-28
    • 2015-02-23
    • 1970-01-01
    相关资源
    最近更新 更多