Nakeuh
Nakeuh

Reputation: 1929

Python Best Practice. Call commandline python file from another python file

I retrieved a python project from some git repo. 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.

I have found different ways of doing so, but I don't know what is the good way to do it.

Upvotes: 1

Views: 71

Answers (2)

tvgriek
tvgriek

Reputation: 1265

You can actually call the main method as long as you make sure args contain the object with the correct attributes. 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'))

Upvotes: 0

BoarGules
BoarGules

Reputation: 16941

Import otherprogram into your own program.

Call otherprogram._main() from the appropriate point in your own code, passing it an argparse.Namespace instance.

You can build that using your own argparse calls if you need to, or just construct the values some other way.

Upvotes: 2

Related Questions