如何以线程形式运行python文件?

时间:2013-05-09 22:39:03

标签: python multithreading python-2.7 pthreads

示例Python父文件:

class myClass( wx.Frame ):
    def __init__(self):
        print "Prepare execute"
        self.MyThread = Thread.RunBackground( './child.py' , ( '--username' , 'root' ) );
        print "Executing... Do you like this app?"
        self.MyThread.start();
    def onClose( self , evt ):
        self.MyThread.close()
        self.exit();

app = MyClass()

我需要知道如何使用Python在后台运行脚本。我们的想法是即使第二个过程有效,也可以使用主窗口。

1 个答案:

答案 0 :(得分:1)

我将在这里猜测:你根本不关心线程,你只想“运行一个脚本”作为“第二个过程”。

这很容易。运行脚本就像运行其他任何东西一样;您使用subprocess模块。由于脚本在一个完全独立的Python解释器实例中运行,在一个完全独立的过程中,“主窗口可以使用,即使第二个进程有效” - 即使它只是旋转或永久阻塞。

例如:

class myClass( wx.Frame ):
    def __init__(self):
        print "Executing... Do you like this app?"
        self.child = subprocess.Popen([sys.executable, './child.py', '--username', 'root'])
    def onClose( self , evt ):
        self.child.wait()
        self.exit();

这里唯一的技巧是作为第一个参数传递的内容。如果要确保child.py由与父级相同的Python副本运行,请使用sys.executable。如果要确保它由默认的Python运行,即使父级使用的是另一个,也请使用python。如果要使用特定路径,请使用绝对路径。如果你想让shell(或者,在Windows上,pylauncher的东西)根据#!行弄清楚它,使用shell=True并只传递./child.py作为第一个参数。等等。