有没有办法做到这一点?我在想也许使用子进程或多进程,但我不知道该怎么做?
我没有任何示例代码,因为这只是一个一般性问题。
有没有办法做到这一点?我在想也许使用子进程或多进程,但我不知道该怎么做?
我没有任何示例代码,因为这只是一个一般性问题。
http://docs.python.org/library/subprocess.html
编辑:可能,我错过了,你想要什么。好吧,我能想象你的问题。
subprocess.call(["ls","-lAd"]) # executes external program. Like system()
# Capture output. Like popen, as I remember.
subprocess.check_output(["echo", "Hello World!"])
os.fork() # Binding to fork()
class MyThread(threading.thread):
def run():
print("Hello from thread")
MyThread().start()
是的,
python 提供了 2 种不同的方法来执行此线程和多处理,您应该使用哪种方法取决于您执行的操作。
主要区别在于线程在同一个解释器中执行函数,而多处理启动一个新的解释器并在该解释器中运行函数。这意味着当您执行 cpu 绑定操作(例如添加大量数字)和线程用于 iobound 操作(例如输入或等待某事发生)时,通常会使用多处理。
线程示例:
from threading import Thread
import time
def fun(a):
global myVar
myVar = "post start" # as you can see myVar is updated and can be read by the main Thread
time.sleep(1)
f = input(a)
print(f"inputed {f}")
myVar = "preThread"
t = Thread(target=fun,
args=("plz input your message ",))
t.start() # start the thread
print("this whil run after the thread started", myVar)
t.join() # wait for thread to finisch executing
print("this whil run after the thread ended", myVar)
输出
this whil run after the thread started post start
plz input your message k
inputed k
this whil run after the thread ended post start
如果您使用多处理库,它会启动一个新的 python 解释器并将所有值复制到其中,并且打印和输入将不起作用
from multiprocessing import Process
import time
def fun(a):
global myVar
myVar = "post start" # as you can see myVar is updated and can be read by the main Thread
time.sleep(1)
f = input(a)
print(f"inputed {f}")
myVar = "preThread"
t = Process(target=fun,
args=("plz input your message ",))
t.start() # start the thread
print("this whill run after the thread started", myVar)
t.join() # wait for thread to finisch executing
print("this whill run after the thread ended", myVar)
输出:
this whill run after the thread started preThread
this whill run after the thread ended preThread
如果您想了解更多信息,请阅读
https://docs.python.org/3/library/threading.html了解线程
https://docs.python.org/3/library/multiprocessing.html了解多处理\