[英]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. 我发现了这样做的不同方法,但是我不知道这样做的好方法是什么。
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.