1、Python 調(diào)試
#!/usr/bin/python
from ftplib import FTP
import sys
import socket
import pdb
def passwordCorrect(ip,port,username,password):
try:
client = FTP()
pdb.set_trace()
client.connect(ip,port)
client.login(username,password)
client.close()
except Exception, e:
pdb.set_trace()
client.close()
if str(e).find('unknown IP address')!=-1:
return 2
return 0
print "correct"
return 1
if __name__ == '__main__':
socket.setdefaulttimeout(3)
ret = passwordCorrect('127.0.0.1',21,'test','test')
print "return is ",ret
主要是pdb模塊的應(yīng)用
在需要設(shè)置斷點(diǎn)的地方加入pdb.set_trace()
執(zhí)行python -m pdb test.py
pdb的常用命令說明:
l #查看運(yùn)行到哪行代碼
n #單步運(yùn)行,跳過函數(shù)
s #單步運(yùn)行,可進(jìn)入函數(shù)
p 變量 #查看變量值
b 行號(hào) #斷點(diǎn)設(shè)置到第幾行
b #顯示所有斷點(diǎn)列表
cl 斷點(diǎn)號(hào) #刪除某個(gè)斷點(diǎn)
cl #刪除所有斷點(diǎn)
c #跳到下一個(gè)斷點(diǎn)
r #return當(dāng)前函數(shù)
exit #退出
上述只是簡(jiǎn)單的調(diào)試,適用于小程序,但如果是大型程序還是相對(duì)來說不方便。
2、Python 命令行參數(shù)獲取
參考學(xué)習(xí)文章:
編寫帶命令行參數(shù)的Python程序
在Python有兩種方式獲取和分析命令行參數(shù),
一是sys.argv,可以訪問所有命令行參數(shù)列表
import sys
print 'Number of arguments:', len(sys.argv)
print 'They are:', str(sys.argv)```
運(yùn)行:
python ./test_argv.py arg0 arg1 arg2
Number of arguments: 4
They are: ['./test_argv.py', 'arg0', 'arg1', 'arg2']
二是通過getopt模塊
-- coding:utf-8 --
import sys, getopt
def main(argv):
inputfile = ""
outputfile = ""
try:
# 這里的 h 就表示該選項(xiàng)無參數(shù),i:表示 i 選項(xiàng)后需要有參數(shù)
opts, args = getopt.getopt(argv, "hi:o:",["infile=", "outfile="])
except getopt.GetoptError:
print 'Error: test_arg.py -i <inputfile> -o <outputfile>'
print ' or: test_arg.py --infile=<inputfile> --outfile=<outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == "-h":
print 'test_arg.py -i <inputfile> -o <outputfile>'
print 'or: test_arg.py --infile=<inputfile> --outfile=<outputfile>'
sys.exit()
elif opt in ("-i", "--infile"):
inputfile = arg
elif opt in ("-o", "--outfile"):
outputfile = arg
print 'Input file : ', inputfile
print 'Output file: ', outputfile
if name == "main":
main(sys.argv[1:])