我想获取一个文件名并将它传递给使用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
你为什么要调用'communicate()'两次? – jsfan
@jsfan第一个是将文件名发送到stdin,第二个是将stdout和stderr接收到变量中,以便可以打印它们。 –
您是否尝试过在一行中执行此操作,即'process.communicate(fileNameByteForm)'? – jsfan