shell向python传递参数

背景

为了便于记录每次执行代码时参数的设置,在shell脚本中调用python代码,并向其传递参数。

问题导入

shell代码

#!/bin/bash
name="xxx"
count=10
python -u click_demo.py --name ${name} --count=${count}

上面的shell脚本中,向python脚本click_demo.py传递了两个参数,namecount
python脚本中怎么接收这两个参数呢?

方式一 通过click传递

click模块基本使用方法参考https://blog.csdn.net/weixin_38278993/article/details/100052961

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo('Hello %s!' % name)


if __name__ == '__main__':
    hello()

方式二 argparse模块

python中argparse使用介绍参考https://blog.csdn.net/Blankit1/article/details/122510221?spm=1001.2014.3001.5501

import argparse
parser = argparse.ArgumentParser() ## 新建参数解释器对象
parser.add_argument('--count',type=int) ## 添加参数,注明参数类型
parser.add_argument('--name') ## 添加参数
args = parser.parse_args()### 参数赋值,也可以通过终端赋值
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        print('Hello %s!' % name)

if __name__ == '__main__':
    hello(args.count,args.name) ## 带参数

注意上述两种方式中,hello函数调用是不同的,使用click模块时,hello不带参数,而使用argparse需要参数。
click版本的 hello 函数有两个参数:count 和 name,它们的值从命令行中获取。

方式三 sys模块

参考http://t.zoukankan.com/sixbeauty-p-4285565.html

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值