Run python script with argparse in another script

匆匆过客 提交于 2021-01-29 06:23:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!