Dirk
Dirk

Reputation: 10111

Import function from Python module that has positional command-line arguments

I have a Python (3.4) module (called 'file_1.py') that uses a positional command line parameter (using argparse) and executes a function on this parameter:

# set up command line parser
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('n', '--number', type=int, required=True, help='some number')

# read command line argument
args = parser.parse_args()
parsed_number = args.number

# function to do some math
def add_one_to_number(x)
    return x+1

# use the function
print(add_one_to_number(parsed_number))

Now, when importing and calling the function from another module ('file_2.py'),

from file_1 import add_one_to_number
print(add_one_to_number(1))

I get the error file_2: error: the following arguments are required: -n/--number

I know that this happens because the imported code is executed after using the import statement and thus asks for the positional command line argument. However, is there a way to import the function without passing the positional command line argument to file_1 in any way? The background is that I want to do some unit testing on the function and as far as I know, testing a unit of code like my function should not depend on the command line parameters that were passed.

Upvotes: 1

Views: 1276

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122027

To prevent the code from running when the module is imported, it is usual to define a main() entry point function and test whether the script is being run directly before calling it:

if __name__ == "__main__":
    main()

In your case, you could do:

import argparse

def parse_args():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser()
    parser.add_argument('n', '--number', type=int, required=True, 
                        help='some number')
    return parser.parse_args()

def add_one_to_number(x):
    """Function to do some math."""
    return x + 1

if __name__ == "__main__":
    args = parse_args()
    print(add_one_to_number(args.number))

Now you can import the two functions without necessarily running them.

Upvotes: 3

Related Questions