【问题标题】:Calling a python script with args from another python script从另一个 python 脚本调用带有 args 的 python 脚本
【发布时间】:2019-03-13 19:12:40
【问题描述】:

我还是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


    【解决方案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

    【讨论】:

      【解决方案2】:

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

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

      scriptA.py:从 scriptB 导入 config_handler

      import multiprocessing
      from scriptB import config_handler
      
      def other_process(*args):
          p = multiprocessing.Process(*args)
          p.start()
      

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

      scriptA.py:调用scriptB.py函数,config_handler

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

      意见:

      根据您提供的信息,我想您可以在没有单独流程的情况下做到这一点。只需按顺序执行所有操作,并使用您在 scriptA.py 中使用的函数使 scriptB.py 成为一个库。

      【讨论】:

        【解决方案3】:

        看来你在旧线程中得到了所有答案,但如果你真的想通过 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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-01
          • 2016-09-03
          • 1970-01-01
          • 1970-01-01
          • 2011-03-04
          相关资源
          最近更新 更多