在另一个脚本中使用 argparse 运行 python 脚本 [英] Run python script with argparse in another script

查看:34
本文介绍了在另一个脚本中使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆