简体   繁体   English

Python最佳实践。 从另一个python文件调用命令行python文件

[英]Python Best Practice. Call commandline python file from another python file

I retrieved a python project from some git repo. 我从一些git repo中检索了一个python项目。 To run this project, there is a file that must be launched by command line with the correct arguments. 要运行此项目,必须使用正确的参数通过命令行启动该文件。 Here is an example : 这是一个例子:

#! /usr/bin/env python

import argparse

parser = argparse.ArgumentParser(description='Description')
parser.add_argument('arg1')
parser.add_argument('arg2')

# %%
def _main(args):
    # Execute the code using args


if __name__ == '__main__':
    _main(parser.parse_args())

I want to use this code in my own project, and so, call the main function from another python file, using a set of predefined arguments. 我想在自己的项目中使用此代码,因此,使用一组预定义的参数从另一个python文件中调用main函数。

I have found different ways of doing so, but I don't know what is the good way to do it. 我发现了这样做的不同方法,但是我不知道这样做的好方法是什么。

  • Calling the file using the os package, but seems like a bad practice to me. 使用os包调用该文件,但是对我来说似乎是一个坏习惯。
  • Refactoring the file so that the main function take the wanted parameters (and getting rid of args object), but it means that command line call would not work anymore. 重构文件,以便主函数使用所需的参数(并摆脱args对象),但这意味着命令行调用不再起作用。
  • Other ? 其他?

Import otherprogram into your own program. 导入otherprogram到自己的程序。

Call otherprogram._main() from the appropriate point in your own code, passing it an argparse.Namespace instance. 从您自己的代码中的适当位置调用otherprogram._main() ,并将其传递给argparse.Namespace实例。

You can build that using your own argparse calls if you need to, or just construct the values some other way. 您可以根据需要使用自己的argparse调用来构建该值,或者以其他方式构建该值。

You can actually call the main method as long as you make sure args contain the object with the correct attributes. 只要确保args包含具有正确属性的对象,就可以实际调用main方法。 Consider this 考虑一下

import argparse

def _main(args):
    print(args.arg1)

_main(argparse.Namespace(arg1='test1', arg2='test2'))

In another file you can do this: 在另一个文件中,您可以执行以下操作:

from some_git_repo import _main
from argparse import Namespace

_main(Namespace(arg1='test1', arg2='test2'))

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

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