2016-03-19 20 views
-1

我想获取一个文件名并将它传递给使用popen的命令。然后我想打印输出。这是我的代码:不知道如何解决popen“无效的文件对象”错误

filePath = tkinter.filedialog.askopenfilename(filetypes=[("All files", "*.*")]) 

fileNameStringForm = (basename(filePath)) 
fileNameByteForm = fileNameStringForm.encode(encoding='utf-8') 

process = subprocess.Popen(['gagner','-arg1'], shell = True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
process .communicate(fileNameByteForm) 

stdout, stderr = process .communicate() <<------ERROR POINTS TO THIS LINE 

stringOutput = stdout.decode('urf-8') 
print(stringOutput) 

我收到以下错误:

ValueError: Invalid file object: <_io.BufferedReader name=9> 

我已经看过其他类似的问题,但没有什么似乎已经解决了我的问题。有些人可以告诉我在代码中哪里出错了吗?

编辑: 如果我是运行在一个命令行命令这将是:

gagner -arg1 < file1 
+0

你为什么要调用'communicate()'两次? – jsfan

+0

@jsfan第一个是将文件名发送到stdin,第二个是将stdout和stderr接收到变量中,以便可以打印它们。 –

+0

您是否尝试过在一行中执行此操作,即'process.communicate(fileNameByteForm)'? – jsfan

回答

1

你在做什么是你在所谓的命令行参数的描述不算什么。您正在执行此操作:

echo "file1" | gagner -arg1 

您需要确保自己传递文件内容。 Popen不会打开并为您读取文件。

按照documentation,什么communicate()确实是

interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate.

所以,一旦你已经运行

process.communicate(fileNameByteForm) 

你的子进程已完成,管道已经被关闭。第二次调用将因此失败。

你想要做的,而不是什么是

stdout, stderr = process.communicate(input_data) 

将管道输入数据到子流程和读取输出和错误。

+0

嗨!感谢您的答复。你知道我能做到这个'gagner -arg1

相关问题