我正在尝试获取文件名并使用 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
最佳答案
您所做的并不是您在假定的命令行参数中所描述的。您实际上正在执行此操作:
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)
它将您的输入数据通过管道传输到子进程并读取标准输出和标准错误。
关于python-3.x - 不知道如何修复 popen ,"Invalid file object"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36096201/