用另一个python脚本中的args调用python脚本

问题描述 投票:1回答:3

我仍然是python的新手,所以提前道歉。我有相关的主题,但没有找到最佳解决方案。 (Run a python script from another python script, passing in args)基本上,我有一个python脚本(scriptB.py),它接受一个配置文件作为参数并做一些事情。我需要从另一个python脚本(scriptA.py)调用此脚本。

如果我没有理由通过,我本可以做到的

import scriptB.py

然而,事情变得不复杂,因为我们需要传递配置文件(mycnofig.yml)作为参数。

其中一个建议是使用;

os.system(python scriptB.py myconfig.yml)

但是,它经常被报告为不是推荐的方法,并且它通常不起作用。

另一个建议是使用:

import subprocess
subprocess.Popen("scriptB.py myconfig.yaml", shell=True)

我不太确定这是否是一种常见做法。

只是想指出两个脚本在脚本中没有任何main。

请告知最好的处理方法。

谢谢,

python arguments call
3个回答
1
投票

这应该工作得很好

subprocess.Popen(['python', '/full_path/scriptB.py', 'myconfig.yaml'], stdout=PIPE, stderr=PIPE)

https://docs.python.org/3/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3


0
投票

如果您确实需要运行单独的进程,那么使用多处理库可能是最好的。我会在scriptB.py中创建一个实际的函数来完成工作。在下面的例子中,我认为config_handler是scriptB.py中的一个函数,它实际上接受了配置文件路径参数。

1.)创建一个函数来处理你的外部python脚本的调用,同时,导入你的脚本和带有参数的方法

scriptA.py: importing config_handler from scriptB

import multiprocessing
from scriptB import config_handler

def other_process(*args):
    p = multiprocessing.Process(*args)
    p.start()

2.)然后只需调用该进程并将您的参数提供给它:

scriptA.py: calling scriptB.py function, config_handler

other_process(name="config_process_name", target=config_handler, args=("myconfig.yml",))

Opinion:

根据您提供的信息,我想您可以设法在没有单独进程的情况下执行此操作。只需按顺序执行操作,并使scriptB.py成为具有您在scriptA.py中使用的函数的库。


0
投票

看来你在旧线程中得到了所有的答案,但是如果你真的想通过os运行它,而不是通过python运行它,这就是我所做的:

from subprocess import run, PIPE, DEVNULL

your_command = './scriptB.py myconfig.yaml'
run(your_command.split(), stdout=PIPE, stderr=DEVNULL)

如果您需要输出:

output = run(your_command.split(), stdout=PIPE, stderr=DEVNULL).stdout.decode('utf-8')

如果scriptB有shebang标题告诉bash它是一个python脚本,它应该正确运行它。

路径可以是相对的也可以是绝对的。

它适用于Python 3.x.

© www.soinside.com 2019 - 2024. All rights reserved.