Python 脚本接收命令行参数的多种方式 All In One
-
sys
-
argparse
-
shell script
-
tensorflow
...
sys
#!/usr/bin/env python3
# coding: utf8
import sys
args = sys.argv
print("args length:", len(args))
print("args type:", type(args))
print("function name:", args[0])
print("first arg =", args[1])
print("second arg =", sys.argv[2])
https://docs.python.org/3/library/sys.html
sys
--- 系统相关的参数和函数¶
https://docs.python.org/zh-cn/3/library/sys.html
argparse
import argparse
parser = argparse.ArgumentParser(description='argparse testing')
parser.add_argument('--name','-n',type=str, default = "bk",required=True,help="a programmer's name")
parser.add_argument('--age','-a',type=int, default=35,help='age of the programmer')
parser.add_argument('--sex','-s',type=str, default='male')
parser.add_argument('--favorite','-f',type=str, nargs="+",required=False,help="favorite of the programmer")
args = parser.parse_args()
print(args.name)
print(args.age)
print(args.sex)
print(args.favorite)
https://docs.python.org/3/library/argparse.html
argparse
--- 命令行选项、参数和子命令解析器
https://docs.python.org/zh-cn/3/library/argparse.html
shell script
# 定义参数
$ ./args.sh arg1 arg2
#!/usr/bin/env bash
# 接收参数
arg1=$1
arg2=$2
# 使用参数
python3 ./test.py $arg1 $arg2
tensorflow
demos
sys
#!/usr/bin/python3
# coding: utf8
import RPi.GPIO as GPIO
import time
import sys
arg1 = sys.argv[1]
print("arg1 =", arg1);
# 指定 BCM 模式下的GPIO 针脚编号
PIN = 12
# BCM 模式
GPIO.setmode(GPIO.BCM)
# 指定 GPIO 针脚为一个电流输出针脚
GPIO.setup(PIN, GPIO.OUT)
# 输出低电平
GPIO.output(PIN, GPIO.LOW)
# index
i = 0
# max
# n = 7
# 类型转换,str => int
n = int(arg1)
print("n =", n)
print('开始闪烁⏳')
while (i < n):
print("i =", i)
# 高电平,LED 点亮
GPIO.output(PIN, GPIO.HIGH)
# 休眠 1 秒,防止 LED 长时间点亮烧坏了
time.sleep(1.0)
# 低电平,LED 熄灭
GPIO.output(PIN, GPIO.LOW)
# 休眠 1 秒
time.sleep(1.0)
i = i + 1
# 输出低电平,LED 关闭
# GPIO.output(PIN, GPIO.LOW)
# 清除,释放内存
GPIO.cleanup()
print('结束闪烁
标签:argparse,Python,arg1,args,sys,命令行,print,GPIO,接收
From: https://www.cnblogs.com/xgqfrms/p/17273858.html