簡體   English   中英

如何將值傳遞給python中正在運行的進程

[英]how to pass a value to running process in python

我想將一些值傳遞給正在運行的進程,該怎么辦?

例如說我有一個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()

那么波彭呢? 您可以將其傳遞給stdin上的進程。

或者,您可以嘗試使用"yes | /tmp/worker.py"類的命令。 yes只是將一堆“ y”轉儲到其stdout中,然后由worker.py拾取。

更簡單的是,使用"echo y | /tmp/worker.py"作為命令。 我只是嘗試過,對我來說效果很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM