2015-10-21 72 views
1

我试图通过给文件夹和文件名称%s调用awk来通过python脚本打开一个文件。awk调用python脚本,因为文件无法打开/读取


import commands  
genotype = 'rice' 

filename = 'model.txt'  
dear = commands.getoutput('''awk '{print $0}' /home/angad/Desktop/Python_result/%s/%s''') % (genotype,filename) 

print dear 

但它返回为:

awk: cmd. line:1: fatal: cannot open file '/home/angad/Desktop/Python_result/rice/model.txt' for reading (No such file or directory) 

有关文件确实存在在那里。 好像我直接写入输入文件路径而不是raw_input(%s),它成功打开并打印文件内容。

+0

所以,如果你输入“stat /home/angad/Desktop/Python_result/rice/model.txt”,你会得到什么? –

回答

2

您的括号中的一个出现在错误的地方。尝试:

dear = commands.getoutput('''awk '{print $0}' /home/angad/Desktop/Python_result/%s/%s''' % (genotype,filename)) 

或者更好的是:

cmd_str = '''awk '{print $0}' /home/angad/Desktop/Python_result/%s/%s''' % (genotype,filename) 
dear = commands.getoutput(cmd_str) 

原因的错误消息显示在你原来的例子正确的文件路径是getoutput的结果,其中包括与%s的错误信息格式仍然存在,正在被打印前被替换。非常误导!

+0

噢,伙计,那个错误的命令的结果是一个字符串,错误信息是由他想使用的值插入的,而不是。哇。尼斯。 –

+0

OP,这就是为什么你应该使用'subprocess',而不是命令。 Stderr与stdout不同,并将它们视为相同的错误。 –

+0

非常感谢汤姆为您排忧解难,这确实是非常具有误导性的,因为我每次都在错误的文件名/路径中检查我的打字错误。 – Angad