1

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 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.