Python 簡(jiǎn)單應(yīng)用

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:])

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容