2016-11-05 90 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行,而该命令似乎只包含一行。然而,替代后,它是两条线,第二条是有问题的。

相关问题