2014-03-05 26 views
0

我想運行一個腳本並返回stdout(輸出)。Popen不拉參數

調用腳本的代碼是:

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?

回答

2

通常,你應該要麼傳遞一個列表,通過與shell=True一個字符串。不是都。

在你的情況下,它看起來並不像你所使用的外殼,所以我只是刪除該關鍵字:

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

這是它,我不能相信這是問題。謝謝。 – BryanGrimes

+0

在我對這個問題的所有問題中,我從來沒有看到不使用shell arg的理由,但我確定這是在某個文檔中。再次感謝。 – BryanGrimes

+0

+1:一個列表參數*和*'shell = True'幾乎總是一個錯誤。 – jfs