简体   繁体   中英

Run python script with argparse in another script

I have a python script which uses some input parameters via argparse.

something like this:

**hello.py**

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", required=True, help="name of the user")
arguments = parser.parse_args()
print(f'Hello, {arguments.name}')

I wonder if this could be ran out in another .py script.

**another.py**

names = ['Lu', 'Li', 'La']
for name in names: 
    import hello.py -n name #this is how to run script from console

Is there any tricky code for this idea?

You can set by default to parse from environment variables.

**hello.py**

import argparse
from os import environ
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", required=True, help="name of the user", default=environ.get("BAR"))
arguments = parser.parse_args()
print(f'Hello, {arguments.name}')

And then modify the environment variables.

**another.py**
from os import environ
names = ['Lu', 'Li', 'La']
for name in names:
    environ["BAR"] = name
    import hello.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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