简体   繁体   English

子流程或导入以在Python中调用脚本

[英]Subprocess or import to invoke a script in Python

I have a script task.py that I am trying to invoke. 我有一个脚本task.py我正在尝试调用。 It seems there are two ways to do that. 似乎有两种方法可以做到这一点。 One is to use the subprocess API while the other is to use Python's import mechanism. 一种是使用subprocess API,另一种是使用Python的导入机制。

task.py task.py

def call_task():
    print("task in progress...")
    return "something"

print("calling task..")
out = call_task()
print("output of the executed task::", out)

Now, we have two approaches to invoke the above task.py python script. 现在,我们有两种方法来调用上面的task.py python脚本。

Approach 1 方法1

import task as task

print("invoke call-task")
out = task.call_task()
print("output::", out)

Approach 2 方法2

import subprocess, shlex, PIPE

proc = subprocess.Popen(shlex.split("python task.py"), stdout = PIPE)
out = proc.communicate()
print("output::", out)

Although both approaches work, which approach is more pythonic? 尽管两种方法都有效,但是哪种方法更适合Python?

Running a separate Python process from Python is frequently an antipattern. 与Python运行单独的Python进程通常是一种反模式。 There are situations where you specifically want two Python instances (for example, if the module you want to use requires its own signal handling etc) but in the absence of factors which force the other choice, import is generally vastly preferrable in terms of usability (you get to call the functions inside the package in an order different from its main flow, and have more fine-grained control over the internals) and performance (starting a separate process is almost always a bad idea if you can avoid it). 在某些情况下,您特别想要两个Python实例(例如,如果要使用的模块需要自己的信号处理等),但是在没有其他因素迫使其他选择的情况下,就可用性而言, import通常是非常可取的(您可以按照与包内部流程不同的顺序调用包内的函数,并对内部结构进行更细粒度的控制)和性能(如果可以避免的话,启动一个单独的进程几乎总是一个坏主意)。

While "The subprocess module allows you to spawn new processes" which executes the code within your task.py, importing will result in the original process executing your code. 虽然“子进程模块允许您生成新进程”在您的task.py中执行代码,但是导入将导致原始进程执行您的代码。

Other than that, it should be identical. 除此之外,它应该是相同的。

You can read more about it in the Python Subprocess Docs 您可以在Python子流程文档中阅读有关此内容的更多信息

As i've seen, its rather unusual to execute python code using an extra subprocess. 如我所见,使用额外的子进程执行python代码非常不寻常。

It may benefit performance wise but the more pythonic way would be importing i guess. 我可能会从性能上受益,但是 更多的pythonic方式将被导入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM