在另一个脚本中使用argparse运行python脚本 [英] Run python script with argparse in another script
本文介绍了在另一个脚本中使用argparse运行python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个python脚本,该脚本通过argparse使用一些输入参数.
I have a python script which uses some input parameters via argparse.
类似这样的东西:
**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}')
我想知道这是否可以在另一个.py脚本中用完.
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}')
然后修改环境变量.
**another.py**
from os import environ
names = ['Lu', 'Li', 'La']
for name in names:
environ["BAR"] = name
import hello.py
这篇关于在另一个脚本中使用argparse运行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文