Python:将wx.py.shell.Shell插入到一个独立进程中
我想创建一个可以控制我用多进程模块创建的独立进程的命令行界面。这可能吗?怎么做呢?
编辑:
我已经找到了一种方法,可以向这个辅助进程发送命令:我在那个进程中创建了一个 code.InteractiveConsole
,并把它连接到一个输入队列和一个输出队列,这样我就可以从主进程中控制这个控制台。不过,我想把它放在一个命令行界面里,可能是 wx.py.shell.Shell
,这样程序的用户就可以使用它。
2 个回答
0
你可以创建一个 Queue
,然后把它传递给一个单独的进程。从Python文档来看:
from multiprocessing import Process, Queue
def f(q):
q.put([42, None, 'hello'])
if __name__ == '__main__':
q = Queue()
p = Process(target=f, args=(q,))
p.start()
print q.get() # prints "[42, None, 'hello']"
p.join()
示例:在wx.py.shell.Shell文档中,构造函数的参数是这样给出的:
__init__(self, parent, id, pos, size, style, introText, locals,
InterpClass, startupScript, execStartupScript, *args, **kwds)
我没有尝试过,但 locals
可能是一个包含本地变量的字典,你可以把它传递给shell。所以,我会尝试以下方法:
def f(cmd_queue):
shell = wx.py.shell.Shell(parent, id, pos, size, style, introText, locals(),
...)
q = Queue()
p = Process(target=f, args=(q,))
p.start()
在shell内部,你应该能够把你的命令放入 cmd_queue
中,然后在父进程中读取这些命令以执行它们。
1
- 首先创建一个外壳
- 把这个外壳和你的应用程序分开,让它的本地变量为空
- 创建你的代码字符串
- 编译这个代码字符串,得到一个代码对象
- 在外壳中执行这个代码对象
from wx.py.shell import Shell frm = wx.Frame(None) sh = Shell(frm) frm.Show() sh.interp.locals = {} codeStr = """ from multiprocessing import Process, Queue def f(q): q.put([42, None, 'hello']) q = Queue() p = Process(target=f, args=(q,)) p.start() print q.get() # prints "[42, None, 'hello']" p.join() """ code = compile(codeStr, '', 'exec') sh.interp.runcode(code)
注意: 我从第一个发帖者那里偷来的 codeStr 可能在这里无法工作,因为有一些序列化的问题。但重点是,你可以在外壳中远程执行你自己的 codeStr。