2017-07-21 54 views
-1

嘿,我正在更新我的腳本,我已經改變os到現在的子進程,但我不知道如何檢查輸出?我想檢查它是空的還是它的內容。腳本只是執行其他程序或句子列表。檢查子進程的輸出python3

""" 
Created on Sun Jan 8 18:52:57 2017 

@author: MarcGrad 
""" 
import sys 
import subprocess 


syntax = ''' 
------------------------------------------------------------------------------------ 
Syntax:  python find_by_sentence.py *file1.txt 
*List of sentences (column of) 
------------------------------------------------------------------------------------ 
''' 
if len(sys.argv) != 1: 
     print(syntax) 
     sys.exit() 

open_file = open(sys.argv[1],'r') 

list_of_sentences = [] 

for sent in open_file: 
    list_of_sentences.append(sent.rstrip()) 
counter = 0 
for word in list_of_sentences: 
    counter += 1 
    print(counter,word) 
    subprocess.check_output("esearch -db protein -query %s | efetch -format fasta >> results_seq.txt" % (word), shell = True) 

print('done :)')  
open_file.close() 
+0

它看起來好像是將輸出連接到文件(results_seq.txt),那麼爲什麼你期望它是任何輸出? 此外,'subprocess.check_output'的返回值是輸出,所以你可以做一些驗證(你也可以通過'stderr = subprocess.STDOUT'獲得stderr) –

+0

只是想知道什麼時候給出的句子有沒有結果:) – MTG

回答

1

當您啓動它有自動開啓3個文件描述符的過程(你可以看看它像單向通信的信道):

  • STDIN - 用於從用戶輸入(例如使用輸入密碼來SSH)
  • STDOUT時 - 同STDOUT但FO使用 - 其被用作應用程序的標準otuput(例如信道用於打印上控制檯消息)
  • STDERR文本錯誤消息。

您可以重定向輸出(還被輸入,但這並不適用於您的問題)的文件(換句話說你「斷開」控制檯和「連接」文件)。重定向指定了這些符號:>>>(有關更多信息,請參閱https://unix.stackexchange.com/questions/171025/what-does-do-vs)。該命令ls -l >> file.txt會寫的ls -l輸出,並在控制檯上寫東西(因爲它是「斷開」)

result = subprocess.check_output(...)需要commannd和「連接」及其STDOUTresult變量。但是你正在運行這個命令:esearch -db protein -query %s | efetch -format fasta >> results_seq.txt,如果你看到最後你會看到>> results_seq.txt。因此,您的命令的輸出已經「連接」到文件results_seq.txt中,並且無法保存在result變量中。

現在你可以使用這些方法:

  1. 運行您的命令是,然後打開文件results_seq.txt並查看內容

    subprocess.check_output("esearch -db protein -query %s | efetch -format fasta >> results_seq.txt" % (word), shell = True) 
    with open("results_seq.txt", "r") as f: 
        result = f.read() 
    
  2. 不要在命令中使用重定向和保存它在Python自己:

    result = subprocess.check_output("esearch -db protein -query %s | efetch -format fasta" % (word), shell = True) 
    with open("results_seq.txt", "wb") as f: 
        f.write(result) 
    
  3. 使用tee這是實用程序允許將輸出重定向到文件,並保持它在控制檯上

    result = subprocess.check_output("esearch -db protein -query %s | efetch -format fasta | tee -a results_seq.txt" % (word), shell = True) 
    

在任何該等例子結束時,您將有存放在變量result

你的命令保存的輸出
+0

謝謝你明確的答案:) – MTG

+0

但不是字符串我得到b''爲每個迭代:( – MTG

+1

'subprocess.check_output'返回字節轉換成str只是調用'decode()'例如' result.decode()' – Qeek