我正在编写一个替代终端窗口(使用 PySide),并且我正在使用以下命令运行 shell(bash):
subprocess.Popen(['/bin/bash','-i'],....
在将各种 stdio 设置为 subprocess.PIPE 时,
我还使用禁用了输出 stdio (out,err) 上的缓冲
fcntl(s.fileno(),F_SETFL,os.O_NONBLOCK)
然后我使用计时器来轮询输出 io 以获取可用数据并拉取它。
它工作得很好,但有时我会遇到一些奇怪的行为。如果在提示符下我发出命令(例如 pwd),我会得到两个不同的可能输出:
/etc:$ pwd
/etc
/etc:$
另一个是
/etc:$ pwd/etc
/etc:$
好像命令中的换行符和输出的其余部分被交换了。基本上任何命令都会发生这种情况,例如,对于 ls,第一个文件出现在 ls 之后,最后一个文件之后出现一个空行。
令我烦恼的是,它并不一致。
编辑:添加了完整的代码示例
#!/usr/bin/python
from PySide import QtCore
from PySide import QtGui
import fcntl
import os
import subprocess
import sys
class MyTerminal(QtGui.QDialog):
def __init__(self,parent=None):
super(MyTerminal,self).__init__(parent)
startPath=os.path.expanduser('~')
self.process=subprocess.Popen(['/bin/bash','-i'],cwd=startPath,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)
fcntl.fcntl(self.process.stdout.fileno(),fcntl.F_SETFL,os.O_NONBLOCK)
fcntl.fcntl(self.process.stderr.fileno(),fcntl.F_SETFL,os.O_NONBLOCK)
self.timer=QtCore.QTimer(self)
self.connect(self.timer,QtCore.SIGNAL("timeout()"),self.onTimer)
self.started=False
def keyPressEvent(self,event):
text=event.text()
if len(text)>0:
if not self.started:
self.timer.start(10)
self.started=True
self.sendKeys(text)
event.accept()
def sendKeys(self,text):
self.process.stdin.write(text)
def output(self,text):
sys.stdout.write(text)
sys.stdout.flush()
def readOutput(self,io):
try:
text=io.read()
if len(text)>0:
self.output(text)
except IOError:
pass
def onTimer(self):
self.readOutput(self.process.stdout)
self.readOutput(self.process.stderr)
def main():
app=QtGui.QApplication(sys.argv)
t=MyTerminal()
t.show()
app.exec_()
if __name__=='__main__':
main()