Tkinter Python脚本未显示shell脚本输出,如mail unix命令

0 投票
1 回答
771 浏览
提问于 2025-04-30 20:14

我有一个Python脚本:

import Tkinter
import subprocess
from Tkinter import *

top = Tkinter.Tk()
top.geometry( "800x600" )

def helloCallBack():
    #print "Below is the output from the shell script in terminal"
    text = Text( top )
    text.insert( INSERT, "*****************************************************\n" )
    text.insert( INSERT, "Below is the output from the shell script in terminal\n" )
    text.insert( INSERT, "*****************************************************\n" )
    p = subprocess.Popen( './secho.sh',                                      \
                          stdout = subprocess.PIPE,                          \
                          stderr = subprocess.PIPE,                          \
                          shell  = True                                      \
                          )
    output, errors = p.communicate()
    #--------------------------------------------------- DEBUG FRAMING STEP 1
    print "DEBUG [stdout] sent:", repr( output ), "<EoString>"
    print "DEBUG [stderr] sent:", repr( errors ), "<EoString>"
    #--------------------------------------------------- DEBUG FRAMING STEP 2
    text.insert( "end", "DEBUG-prefix-to-validate-Tkinter-action.<BoString>" \
                       + output                                              \
                       + "<EoString>"                                        \
                       )
    text.pack()
    #--------------------------------------------------- DEBUG FRAMING STEP 3
    print "DEBUG FRAMING <EoCall>"

B = Tkinter.Button( top, text ="Hello", command = helloCallBack )

B.pack()
top.mainloop()

当我的shell脚本secho.sh里有一些简单的命令,比如ls时,程序的输出是正常的,像下面的截图那样。(我不能上传图片,因为我是Stack Overflow的新手)

http://tinyurl.com/tkinterout

但是如果我的shell脚本比较复杂,即使它只有一行,比如:

mail -f ~/Desktop/Test/Inbox.mbox

显示的内容只是“下面是输出....”而没有其他任何东西。

我查阅了这个这个以及许多其他相关的Stack Overflow帖子,但我没有找到满意的答案,因为我找到的帖子都没有处理像mail这样的命令(这个命令在执行后允许用户与终端互动)。

我该如何解决这个问题呢?

暂无标签

1 个回答

0

这里有一个我在上面评论中提到的第二种替代方案的工作示例。

import subprocess as sp

p = sp.Popen('''python -i -c "print('hello world')"''', stdin=sp.PIPE,
             stdout=sp.PIPE, stderr=sp.PIPE, universal_newlines=True)
out, err = p.communicate(input='quit()')
print("out = {}err = {}".format(out, err))

打印结果是

out = hello world
err = >>> ... 

如果没有设置 universal_newlines=True,那么输入参数必须是字节类型:p.communicate(input=b'quit()')。看起来控制台解释器的提示信息是发送到错误输出(stderr),而不是标准输出(stdout)。

撰写回答