python脚本传递参数
2024-08-31 19:04:39
给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
PyCharm 下运行python脚本并传递参数
编辑脚本:
Alt + Shift + F10 执行
报错
传递参数的方法:
Alt + Shift + F10 弹出
选择:Edit configurations 弹出
在左侧选择要传入参数的文件,在右侧Configuration-->Script parameters 中添加要传递的参数 --> RUN
执行结果:
最新文章
- 移动站适配rel=alternate PC页和H5页适配标注
- 在eclipse中遇到cannot open output file xxx.exe: Permission denied 的解决办法
- ArtDialog文档
- mysql Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT
- java基础篇-jar打包
- nedb nodejs 数据库学习
- *像word一样编辑复杂的文本:SpannableString 样式详介
- php技术概要汇总
- 关于H5中的Canvas API的探索
- HTTP缓存控制总结
- LDA 线性判别分析
- 使用sklearn进行数据挖掘-房价预测(2)—划分测试集
- DotNetCore跨平台~System.DrawingCore部署Linux需要注意的
- Scala + IntelliJ IDEA
- 最小二乘法多项式曲线拟合原理与实现 zz
- 《Scrum实战》读书会作业01 - 用知行视角总结现在或者过去的一个项目
- 转:XML 中的空白字符须知:xml:space
- 3. IP地址转换函数
- C++ std::vector
- MVC dropdownlist 下拉框
热门文章
- uncompressing linux .................................................后没反应解决办法
- Python9-From-CSS-day48
- 动态规划:HDU1059-Dividing(多重背包问题的二进制优化)
- [Hdu3507]Print Article(斜率优化)
- 使用python实现简单爬虫
- git---gui使用
- UnicodeDecodeError: &#39;ascii&#39; codec can&#39;t decode byte 0xe4 in position 19: ordinal not in range(128)
- 试水新的Angular4 HTTP API
- WordPress 通过文章 URL 获取文章 ID
- python正则表达式应用优化实例