2016-11-05 89 views
0

當我在bash中運行腳本時,出現錯誤:sh: 2: Syntax error: "|" unexpected。我不知道爲什麼,我想在這裏使用管道,並且使用該命令的perl腳本能夠工作,但我需要Python。輸入(文本文件)的傳遞給os.system()的shell命令失敗:sh:2:語法錯誤:「|」意外的

例子:

Kribbella flavida 
Saccharopolyspora erythraea 
Nocardiopsis dassonvillei 
Roseiflexus sp. 

腳本:

#!/usr/bin/python 

import sys import os 

input_ = open(sys.argv[1],'r') output_file = sys.argv[2] 
#stopwords = open(sys.argv[3],'r') 



names_board = [] 

for name in input_: 
    names_board.append(name.rstrip()) 
    print(name) for row in names_board:  
    print(row)  
    os.system("esearch -db pubmed -query %s | efetch -format xml | xtract -pattern PubmedArticle -element AbstractText >> %s" % (name, 
output_file)) 
+2

如果用'print'替換'os.system',會得到什麼?這看起來合理嗎? –

+0

你在使用什麼操作系統?你讀過「man esearch」,「man efetch」和「man xtract」嗎? –

+0

這個ubuntu,但這個程序是ncbi的eutilies。 – MTG

回答

2

可能無關的問題是你沒有正確引述該命令的輸入和輸出文件名。使用

os.system('esearch -db pubmed -query "%s" | efetch -format xml | xtract -pattern PubmedArticle -element AbstractText >> "%s"' % (name, output_file)) 

然而,即使這不是萬無一失的所有法律文件名(如包含雙引號的文件名)。我建議使用subprocess模塊代替os.system,而使殼出來的過程的共

esearch = ["esearch", "-db", "pubmed", "-query", name] 
efetch = ["efetch", "-format", "xml"] 
xtract = ["xtract", "-pattern", "PubmedArticle", "-element", "AbstractText"] 
with open(sys.argv[2], "a") as output_file: 
    p1 = subprocess.Popen(esearch, stdout=subprocess.PIPE) 
    p2 = subprocess.Popen(efetch, stdin=p1.stdout, stdout=subprocess.PIPE) 
    subprocess.call(xtract, stdin=p2.stdout, stdout=output_file) 
1

的問題是,name包含終止從輸入讀出的行中的換行。當您在shell命令中插入name時,換行符也被插入,然後shell將其視爲第一個命令的結尾。但是,第二行然後以管道符號開始,這是一個語法錯誤:管道符號必須位於同一行上的命令之間。

一個很好的提示,說明問題出在sh報告錯誤第2行,而該命令似乎只包含一行。然而,替代後,它是兩條線,第二條是有問題的。

相關問題