使用Python在新进程中执行函数

时间:2012-07-07 03:07:06

标签: python multithreading subprocess multiprocessing

有办法做到这一点吗?我想也许可以使用子进程或多处理,但我不知道该怎么做?

我没有任何代码示例,因为它只是一个普遍的问题。

2 个答案:

答案 0 :(得分:0)

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()

答案 1 :(得分:0)


python 提供了 2 种不同的方法来执行此线程和多处理,您应该使用一种取决于您执行的操作。
主要区别在于线程在同一个解释器中执行函数,而多处理启动一个新的解释器并在该解释器中运行该函数。这意味着当您执行 cpu 绑定操作(例如添加大量数字)和 Thread 用于 iobound 操作(例如输入或等待某事发生)时,通常会使用多处理。
线程示例:

Encoding.UTF8

输出

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)

如果您使用多处理库,它会启动一个新的 Python 解释器并将所有值复制到其中,并且打印和输入将不起作用

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

输出:

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)

如果你想了解更多请阅读
https://docs.python.org/3/library/threading.html 用于线程
https://docs.python.org/3/library/multiprocessing.html 用于多处理\