Python命令行传参之sys.argv

介绍

实际工作中,我们往往希望在运行程序时来指定需要传入的参数,比如传入指定的learning rate,batch size等等,使用sys.argv会是一个很方便的方式。

用法

我们通过一个实例来演示一下sys.argv的使用,首先创建一个Python脚本test.py

import sys
  
name = sys.argv[1]    # 参数1
age = sys.argv[2]    # 参数2

intro = "Hello, my name is {0} and I'm {1} years old.".format(name,age)

print('This is file ',sys.argv[0])    # 0号参数表示自身
print(intro)

然后运行一下

python test.py doghead 6
# This is file  test.py
# Hello, my name is doghead and I'm 6 years old.

简单!

猜你喜欢

转载自www.cnblogs.com/mrdoghead/p/12228971.html