I want to pass some values to a running process, how can I do that ?
say for example I have a worker.py and it has this code.
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()
and this file is a executable file. And I have another python file in that file I am using commands to start my worker.py like this.
status, message = commands.getstatusoutput ("/tmp/worker.py")
but command can't go next level because of the raw_input.
Is there anyway I can pass "y" to worker through commands or subprocess ?.
PS : I am running this command through a pyqt gui.
Thanks in advance.
UPDATE :
I found it at last and here is my solution, and yes its using pexpect.
fully working solution of my problem. I hope it will help some in else in future :)
#!/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()