我在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 terminaln" )
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
)时,程序会正常输出,如下面的屏幕截图所示。(我无法在这里上传图片,因为我是一个新手,无法叠加溢出)http://tinyurl.com/tkinterout
如果我有一些复杂的shell脚本,即使它是一个单行,例如:
mail -f ~/Desktop/Test/Inbox.mbox
显示的只是文本"下面是输出……",没有其他内容
我已经提到了这个,这个和很多其他的栈溢出相关的帖子。但我没有得到一个令人满意的答案,因为我发现没有一个能处理诸如邮件之类的命令(它允许用户在执行命令后与终端交互)。
如何解决这个问题?
这是我在上面的评论中建议的第二种替代方案的一个工作示例。
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
,则输入arg必须是字节:p.communicate(input=b'quit()')
。控制台解释器似乎提示转到stderr,而不是stdout。