簡體   English   中英

如何以線程方式運行python文件?

[英]how to run a python file as Thread?

示例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在后台運行腳本。 這個想法是,即使第二個進程起作用,也可以使用主窗口。

我將在這里猜測:您根本不關心線程,您只想“運行腳本”作為“第二個進程”。

這很容易。 運行腳本就像運行其他任何東西一樣。 您使用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 ,請使用python 如果要使用特定路徑,請使用絕對路徑。 如果您想讓外殼程序(或者在Windows中,是pylauncher之類的東西)根據#!來計算出來#! 行,使用shell=True並僅將./child.py作為第一個參數傳遞。 等等。

暫無
暫無

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

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