簡體   English   中英

如何從另一個 Python 腳本運行 Python 腳本

[英]How to run a Python Script from another Python Script

我有一個 python 腳本,它檢測來自網絡攝像頭或視頻的運動。 我需要一個 GUI 來啟動這個 python 腳本。 我使用 PyQt5 Designer 創建了我的 GUI,我想單擊一個按鈕來打開我的motion_detector.py

這是我的代碼。

我在 GUI 中有一個按鈕

  self.pushButton.setObjectName("pushButton")

我嘗試通過單擊此按鈕打開我的motion_detector.py

  self.pushButton.clicked.connect(lambda:os.system('python motion_detector.py'))

在我的代碼頂部,我導入了"os" ,並將我的 GUI 文件untitled.py和我的motion_detector.py放在同一目錄中。 當我嘗試運行時,它給了我一個錯誤

  python: can't open file 'motion_detector.py': [Errno 2] No such file or directory

感謝您的幫助!

您可以使用 subprocess 或 os 模塊。 我更喜歡子進程,因為它更安靜,並且它會為您存儲輸出和錯誤代碼(如果有的話) - 在這兩種情況下,不要忘記將完整路徑放在腳本和 python.exe 中(除非您將它的路徑放在到 %PATH% 變量)

os.system 的語法是:

os.system("<path to python> <path to your script>")

subprocess.Popen 的語法是:

proc = subprocess.Popen(t"<path to python>", "<path to your script>"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
stdout, stderr = proc.communicate()

暫無
暫無

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

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