2017-10-13 29 views
0

我正在使用speedtest-cli來獲得我的互聯網速度在python腳本。我想通過subprocess.Popen在shell中運行這個命令。管道命令似乎有幾個單獨的輸出到文件

以下是在終端的命令:

`speedtest-cli --share > output.log` 

speedtest-cli運行測試,同時--share爲我提供了在輸出的附加鏈路,指向SPEEDTEST結果的圖像。這裏是output.log內容:

檢索speedtest.net配置......從M-NET(xxx.xxx.xxx.xxx)... 檢索speedtest.net服務器列表 測試... 基於ping選擇最好的服務器... 主持人XXXXXXXXXXXXXXXXXXXXXX [16.12 km]:20.902 ms 測試下載速度.......................... .................................................. ... 下載:48.32 Mbit/s 測試上傳速度................................... .................................................. ................. 上載:12.49 Mbit/s 分享結果:http://www.speedtest.net/result/670483456.png

如果我在終端運行命令,我會得到所有測試結果以及目標文件中的鏈接。我證實,它是所有stdout,並通過使用該grep trick不是另一個通道:command | grep .

我想在Python運行如下:

subprocess.Popen(['speedtest-cli', '--share', '>', 'output.log`], 
        stdout=subprocess.PIPE, shell=True) 

...我也試圖把輸出入文件直接通過python:

with open('output.log', 'w') as f: 
    Popen(['speedtest-cli', '--json', '--share'], stdout=f, shell=True) 

這些都沒有工作。我用後一種方法得到一個很好的文件,但鏈接不包括在內! (上面輸出中的最後一行)。

反對貶低和更好的安全性與使用subprocess模塊所有的警告,我變得絕望,並試圖os.system()

os.system('speedtest-cli --share > output.log') 

煩人,這個工程......全部輸出與鏈接一起在被捕獲文件。

這是怎麼回事?如何使用Popen獲取鏈接?

我正在使用Python 3。5

回答

2

使用shell=True,你的論點來Popen需要是,而不是一個列表:

subprocess.Popen('speedtest-cli --json --share > output.log', 
       stdout=subprocess.PIPE, shell=True) 

比較:

>>> subprocess.Popen('echo hello', shell=True) 
>>> hello 

和:

>>> subprocess.Popen(['echo', 'hello'], shell=True) 
>>> 

當你通過一個列表和喲你正在使用shell=True,只有第一項是相關的,其餘的被忽略。

如果你想自己收集輸出,考慮subprocess.check_output

>>> output = subprocess.check_output(['echo', 'hello']) 
>>> output 
b'hello\n' 

或者:

>>> output = subprocess.check_output('echo hello', shell=True) 

check_output方法既Python 2和Python 3的作品在Python 3,你也有可用的run方法。

+0

謝謝 - 我只需要創建一個字符串。在你的第一個代碼示例中,你將單個字符串作爲一個列表,它不起作用 - 是否應該糾正? –

+0

實際上,它工作正常(「...只有第一個項目是相關的,其餘部分被忽略...「),但是這是一個錯字,我已經修復了它 – larsks

+0

shell = True是一個安全噩夢,所以最好使用shell = False並傳遞一個參數列表(這不是一個安全問題)因爲它只有在攻擊者可以控制其中一個參數時才被利用,但是最好避免它) – user9876

相關問題