python-3.x - 不知道如何修复 popen ,"Invalid file object"错误

标签 python-3.x tkinter

我正在尝试获取文件名并使用 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 不会为您打开和读取该文件。

根据documentationcommunicate() 的作用是

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/

相关文章:

python-3.x - Haskell 中的左右字符串对齐

python-3.x - matplotlib 中的 imhsow 显示与 opencv 不同

python - 用多种颜色为 Tkinter 按钮着色

python - 类型错误 : metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

python - 在 tkinter 脚本中使用 pyperclip 保存到剪贴板时进行编码

python - WSL——未找到命令

python - Matplotlib 范围与 mollweide 投影

Python-xlsxwriter 在使用csv数据时只写成文本

python - 在 Python : Getting "name ' Tk' is not defined"only at Command Prompt, 中编程在 IDLE 中工作

python - 绑定(bind)Tkinter按钮: function takes exactly 1 positional argument (0 given)