簡體   English   中英

子進程Popen無法捕獲wget --spider命令結果

[英]Subprocess Popen not capturing wget --spider command result

我對將子流程命令的輸出捕獲為字符串的理解是設置stdout=sucprocess.PIPE並使用command.communicate()捕獲result, error

例如,鍵入以下內容:

command = subprocess.Popen(["nmcli", "con"], stdout=subprocess.PIPE)
res, err = command.communicate()

不會向終端產生任何輸出,並且將我的所有連接信息作為字節文字存儲在變量res中。 簡單。

但是在這里對我來說卻是崩潰了:

url = "http://torrent.ubuntu.com/xubuntu/releases/trusty/release/desktop/xubuntu-14.04.1-desktop-amd64.iso.torrent"
command = subprocess.Popen(["wget", "--spider", url], stdout=subprocess.PIPE)

這會將命令的輸出打印到終端,然后暫停執行,直到用戶輸入了擊鍵。 隨后運行command.communicate()返回一個空字節文字b''

對我來說特別奇怪的是執行的暫停,因為以bash發出命令只是打印命令結果並直接返回提示。

我所有的搜索都只是找到有關如何捕獲子過程結果的常見問題解答,而與某些必須以不同方式捕獲某些命令的問題或關於wget和子過程的任何特定問題無關。

附加說明,我已經能夠將wget命令與子--spider一起使用來下載文件(沒有--spider選項)而沒有問題。

任何幫助,不勝感激,這讓我感到難過。

wget從來沒有問過我任何事情,但是某些進程(例如ssh)確實捕獲了終端設備(tty)以獲取密碼,從而縮短了您設置的進程管道。

要使這種情況自動化,您需要偽造一個終端而不是普通管道。 有一些使用termios和其他東西的食譜,但是我的建議是使用模塊“ pexpect”來編寫代碼。

stderr正在捕獲輸出,因此由於您沒有管道stderr,因此在運行命令且stdout為空時會看到輸出:

url = "http://torrent.ubuntu.com/xubuntu/releases/trusty/release/desktop/xubuntu-14.04.1-desktop-amd64.iso.torrent"
command = Popen(["wget", "--spider", url],stdout=PIPE,stderr=PIPE)
out,err = command.communicate()

print("This is stdout: {}".format(out))
print("This is stderr: {}".format(err))
This is stdout: b''
This is stderr: b'Spider mode enabled. Check if remote file exists.\n--2015-02-09 18:00:28--  http://torrent.ubuntu.com/xubuntu/releases/trusty/release/desktop/xubuntu-14.04.1-desktop-amd64.iso.torrent\nResolving torrent.ubuntu.com (torrent.ubuntu.com)... 91.189.95.21\nConnecting to torrent.ubuntu.com (torrent.ubuntu.com)|91.189.95.21|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 37429 (37K) [application/x-bittorrent]\nRemote file exists.\n\n'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM