【发布时间】:2012-06-14 01:14:11
【问题描述】:
我想将一些值传递给正在运行的进程,我该怎么做?
比如说我有一个worker.py,它有这个代码。
import os
import sys
def my_test():
print " I am starting now"
a = raw_input("Do you want to start ? ")[0].lower()
if a == "y":
print "Yes I am starting now"
my_test()
这个文件是一个可执行文件。我在那个文件中有另一个 python 文件,我正在使用命令来启动我的 worker.py。
status, message = commands.getstatusoutput ("/tmp/worker.py")
但由于 raw_input,命令无法进入下一个级别。
无论如何我可以通过命令或子进程将“y”传递给工作人员吗?
PS:我正在通过 pyqt gui 运行此命令。
提前致谢。
更新:
我终于找到了,这是我的解决方案,是的,它使用 pexpect。
我的问题的完全有效的解决方案。我希望它会在未来对其他人有所帮助:)
#!/usr/bin/python
import sys
import pexpect
import re
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Message box')
qbtn = QtGui.QPushButton('Quit', self)
qbtn.clicked.connect(self.spawnJob)
self.qtxte = QtGui.QPlainTextEdit(self)
qbtn.resize(qbtn.sizeHint())
qbtn.move(260, 150)
self.setGeometry(300, 300, 340, 200)
self.setWindowTitle('Quit button')
self.show()
def spawnJob(self):
self.child = pexpect.spawn ('/usr/local/bin/python /tmp/worker.py')
a = self.child.expect ('Do you')
if str(self.child.after) == 'Do you':
self.test_one()
before_msg = self.child.before
self.qtxte.appendPlainText(before_msg)
for ln in self.child.readlines():
self.qtxte.appendPlainText(ln.rstrip())
def test_one(self):
reply = QtGui.QMessageBox.question(self, 'Message',
"Are you sure to quit?", QtGui.QMessageBox.Yes |
QtGui.QMessageBox.No, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
self.child.sendline ('y')
else:
self.child.kill(0)
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
【问题讨论】:
-
看看 pexpect (noah.org/wiki/pexpect)。
-
谢谢,我会检查一下这个问题和一个快速的问题,我是否可以在任何时候使用 child.sendline 或者它应该在我创建对象时通过?
-
我在 pexpect 中发现的唯一问题是在 sendline 之后我无法获取日志,也许我错了会有一些选项。
标签: python subprocess threadpool