show | version | enable_checker |
---|---|---|
step |
1.0 |
true |
- 上次研究了python文件运行时的系统参数
- sys.argv
- 通过sys.argv就可以接收从命令行来的参数了
- 可以通过索引来获得第n个参数
- 这就是索引(index)的作用
- 但是调用实际过程中
- 参数可能给
- 也可能没给
- 这可怎么办呢?
import sys
fruit = sys.argv[1]
amount = int(sys.argv[2])
if fruit == "apple":
sum = amount * 1
print("Sum of",amount, "apples are", sum)
elif fruit == "banana":
sum = amount * 0.5
print("Sum of",amount, "bananas are", sum)
else:
print("There is no price of",fruit)
- 参数没给够
- 发生了IndexError
import sys
try:
fruit = sys.argv[1]
amount = int(sys.argv[2])
if fruit == "apple":
sum = amount * 1
print("Sum of",amount, "apples are", sum)
elif fruit == "banana":
sum = amount * 0.5
print("Sum of",amount, "bananas are", sum)
else:
print("There is no price of",fruit)
except IndexError:
print("Program needs argument!")
print("eg. python3 shopping apple 5")
- 运行结果
- 这样就足够了吗?
- 在str转化为int时后
- 有可能出现ValueError
- ValueError 是我们的老朋友了
- 又该如何修改呢?
import sys
try:
fruit = sys.argv[1]
amount = int(sys.argv[2])
if fruit == "apple":
sum = amount * 1
print("Sum of",amount, "apples are", sum)
elif fruit == "banana":
sum = amount * 0.5
print("Sum of",amount, "bananas are", sum)
else:
print("There is no price of",fruit)
except IndexError:
print("Program needs argument!")
print("eg. python3 shopping apple 5")
except ValueError:
print("last arguement needs integer!")
print("eg. python3 shopping apple 5")
- 运行
- 确实解决了问题
- 这个程序可以调试吗?
pdb3 shopping.py apple 5
- 运行结果
- 定义三个断点
- 1 号断点在 第2行
- 2 号断点在 第15行
- 3 号断点在 第17行
- 这些断点是彼此什么关系呢?
- 其实我们调试的时候
- 这些断点构成一个列表(list)
- mutable sequence
- clear命令
- 可以删除断点
- clear shopping.py:2
- 删除 a.py第2b行 断点
- clear 3
- 删除 当前第3号 断点
- clear
- 清空 断点列表
- 把断点删除后
- 在1、14、17行上设置断点
- 走流程
- c 就是continue
- 继续走到下一个断点
- 由于参数正确直接跳转到了结尾
- 可以在运行的时候修改sys.argv吗?
- 开始执行
- 把系统参数列表给清空了
- 再continue会如何呢?
- 出现了IndexError
- 因为sys.argv被清空了
- 进入了第14行
- 处理异常
- 我们退出了去总结吧
- 我们这次完善了系统参数列表的处理
- 处理了可能出现的
- IndexError
- ValueError
- 处理了可能出现的
- 调试了程序
- 理解到断点本身就是一个列表
- 而且在调试的过程中
- 可以对于变量进行修改
- 列表还有什么方法吗?🤔🤔
- 下次再说 👋