问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/63828048/run-python-script-with-argparse-in-another-script