python脚本传递参数

时间:2019-12-03
本文章向大家介绍python脚本传递参数,主要包括python脚本传递参数使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

 

给python程序传递参数

运行python脚本时有时需要执行实传递参数

在linux下:

[root@Test ~]# cat /opt/python.py 
#!/usr/local/bin/python
# -*- coding:utf-8 -*-

import sys

print(sys.argv[0])          #sys.argv[0] 类似于shell中的$0,但不是脚本名称,而是脚本的路径   
print(sys.argv[1])          #sys.argv[1] 表示传入的第一个参数,既 hello

#运行结果:

[root@Test ~]# python /opt/python.py hello
/opt/python.py       #打印argv[0]  脚本路径
hello                      #打印argv[1]  传入的参数 hello

在windows 下:

打开CMD或powershell,切换到python脚本所在位置,使用python filename.py执行脚本

#编辑  D:\Python\Study\python.py
#内容如下:
#!/usr/bin/env python
# -*-coding:utf-8 -*-

import sys

print(sys.argv[0])
print(sys.argv[1])

进入powershell  
PS C:\Windows\system32> cd D:\Python\Study   #进入目录

PS D:\Python\Study> python python.py     #执行python脚本 (未传参数)
python.py                                                    #报错信息
Traceback (most recent call last):
  File "python.py", line 7, in <module>
    print(sys.argv[1])
IndexError: list index out of range

PS D:\Python\Study> python python.py hello  #传入参数(正常运行)
python.py
hello

或以绝对路径执行:
PS D:\Python\Study> python D:\Python\Study\python.py hello
D:\Python\Study\python.py
hello

原文地址:https://www.cnblogs.com/php-linux/p/11978051.html