2014-01-20 79 views
1

我正在尋找解決方案來讀取python子進程中的「更改」/「移動」輸出(cURL具體)。由於某些原因,我不能使用pycurl,我只有二進制文件。獲取更改輸出python子進程

顯然,這種代碼是行不通的:

import subprocess 
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE) 
out, err = p.communicate() 

你有什麼我可以做檢索捲曲數據的想法(速度,ETA,...)?

+0

是你真正想要的捲曲數據? – RyPeck

回答

0

您可以使用select來獲取asnyc輸出。 例如: -

$ tree 
. 
├── async_output.py 
└── changing_output.sh 

PY代碼:

$ cat async_output.py 
from subprocess import PIPE, Popen 

#proc = Popen(['curl', 'http://www.baidu.com'], stdin = PIPE, stderr = PIPE, stdout = PIPE) 
proc = Popen(['changing_output.sh'], stdin = PIPE, stderr = PIPE, stdout = PIPE) 
while proc.poll() == None: 
    import fcntl 
    import os 
    import select 
    fcntl.fcntl(
      proc.stdout.fileno(), 
      fcntl.F_SETFL, 
      fcntl.fcntl(proc.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK, 
      ) 

    fcntl.fcntl(
      proc.stderr.fileno(), 
      fcntl.F_SETFL, 
      fcntl.fcntl(proc.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK, 
      ) 

    while proc.poll() == None: 
     readx = select.select([proc.stdout.fileno()], [], [], 0.1)[0] 
     readx_err = select.select([proc.stderr.fileno()], [], [], 0.1)[0] 
     if readx: 
      chunk = proc.stdout.read() 
      print chunk, 
     elif readx_err: 
      chunk = proc.stderr.read() 
      print chunk, 
     else: 
      break 
proc.wait() 

SH代碼:

$ cat changing_output.sh 
#!/usr/bin/env bash 

for i in `seq 1 10`; do 
    echo $i 
    sleep 1 
done 
0

UPDATE:我錯過了您正在查找速度數據的事實。你可以自己計算一下,因爲你可以在傳輸之前和之後調用time.time(),並且你可以計算傳輸的字節數。像這樣:

import subprocess 
import time 

start_time = time.time() 
out = subprocess.check_output([ 
    'curl', '--silent', 'http://google.com/']) 
end_time = time.time() 
bytes_per_sec = len(out)/(end_time-start_time) 
+0

如果你注意到他的問題,他想要速度數據。 – RyPeck

+0

啊,我完全錯過了。在那種情況下,我會盡我所能在這段代碼中做些什麼,但在前後調用'time.time()'並自己計算速度。 – larsks

+0

事實上,只要我能像你一樣快速輸入,我本可以爲你節省額外的評論! – larsks