如何从第一个 运行 第二个 Python 脚本?

How to run second Python script from first one?

我正在尝试从第一个脚本 运行 第二个 python 脚本。第二个脚本是运行只在满足条件的时候

这是我糟糕的代码:

if T == 1 or O == 24 or V == 8 or Z == 45:
        subprocess.call([r'app_virtual_helper.bat'])

(批处理文件正在打开第二个 python 脚本)

一切正常,但是当新脚本 运行ning 时,第一个停止工作。

如何在 if is true 时打开第二个脚本并且仍然有第一个脚本 运行ning?

试试这个:

process = subprocess.Popen([r'app_virtual_helper.bat'])

这样您的脚本就不会等待第二个脚本的调用结束

此代码在单独的线程中运行第二个文件,因此第一个脚本保持 运行 并且在您调用第二个文件时不会停止

from threading import thread

if T == 1 or O == 24 or V == 8 or Z == 45:

   test = Thread(target=call, args=(r'app_virtual_helper.bat'))
   test.start()

没有穿线:

script1.py的内容:

subprocess.call("python script2.py")

输出:

>python script1.py
Starting script1 function..
Script1 running.. 0
Script1 running.. 1
Script1 running.. 2
Script1 running.. 3
Launching second script..
Script2 running.. 0
Script2 running.. 1
Script2 running.. 2
Script2 running.. 3
Running script1 function again..
Script1 running.. 0
Script1 running.. 1
Script1 running.. 2
Script1 running.. 3

带线程:

script1.py的内容:

import time
import subprocess
import threading

def run():
    for i in range(4):
        print("Script1 running..", i)
        time.sleep(1)

print("Starting script1 function..")
run()
print("Launching second script..")
t = threading.Thread(target=subprocess.call, args=("python script2.py", True))
t.start()
print("Running script1 function again..")
run()

输出:

>python script1.py
Starting script1 function..
Script1 running.. 0
Script1 running.. 1
Script1 running.. 2
Script1 running.. 3
Launching second script..
Running script1 function again..
Script1 running.. 0
Script2 running.. 0
Script1 running.. 1
Script2 running.. 1
Script1 running.. 2
Script2 running.. 2
Script1 running.. 3
Script2 running.. 3

script2.py的内容:

import time

def run():
    for i in range(4):
        print("Script2 running..", i)
        time.sleep(1)

run()

如果您在第一个脚本中依赖第二个脚本中的 returns,这会使事情变得有点困难,但这是可能的。这为您提供了前面提到的 subprocess.Popen() 方法的优势。希望这有助于您入门。