【发布时间】:2013-07-13 23:02:20
【问题描述】:
我正在使用 wxPython 工具包设计一个 GUI,这意味着它是用 python2 编写的。但是,我想将 python3 用于实际的应用程序代码。我将如何从 GUI 调用我的 python3 代码?
【问题讨论】:
标签: python python-2.7 python-3.x
我正在使用 wxPython 工具包设计一个 GUI,这意味着它是用 python2 编写的。但是,我想将 python3 用于实际的应用程序代码。我将如何从 GUI 调用我的 python3 代码?
【问题讨论】:
标签: python python-2.7 python-3.x
通过管道或套接字交谈
尽可能从__future__ 启用此类python 3 功能,或使用six 之类的库来编写与两者兼容的代码。
不要这样做。
最后,你确定不能在 Python 3 中使用 wxPython 吗?在线文档中没有任何内容说您不能。
【讨论】:
您可以将应用程序代码作为 shell 脚本运行。
from subprocess import call
exit_code = call("python3 my_python_3_code.py", shell=True)
你也可以像往常一样传入终端参数。
arg1 = "foo"
arg2 = "bar"
exit_code = call("python3 my_python_3_code.py " + arg1 + " " + arg2, shell=True)
如果您想从应用程序收集更多信息,您可以捕获标准输出,如下所述:Capture subprocess output
如果您想在两个方向上流畅地通信,最好使用管道或套接字。
【讨论】:
shell=True 是不必要的。 subprocess.call() 等待脚本完成——它将挂起 GUI。 OP 可能想要运行 multiple 命令,即 python3 进程应该启动一次,然后你应该使用管道/套接字其他 IPC 方法,如 @Marcin 的回答中所建议的那样。这是Gtk code example that shows how to read subprocess output in a GUI application (using threads or async.io)。这是Tkinter code example (async) 和using threads
shell=True在有参数的时候是必须的,否则会报错:FileNotFoundError: [Errno 2] No such file or directory。我用它从 Python 3 调用 Python 2 代码。