美文网首页python
Python 简单应用

Python 简单应用

作者: lifesmily | 来源:发表于2017-04-29 20:47 被阅读31次

1、Python 调试

#!/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模块的应用
在需要设置断点的地方加入pdb.set_trace()
   执行python -m pdb test.py
pdb的常用命令说明:
  l #查看运行到哪行代码
  n #单步运行,跳过函数
  s #单步运行,可进入函数
  p 变量 #查看变量值
  b 行号 #断点设置到第几行
  b #显示所有断点列表
  cl 断点号 #删除某个断点
  cl #删除所有断点
  c #跳到下一个断点
  r #return当前函数
  exit #退出
上述只是简单的调试,适用于小程序,但如果是大型程序还是相对来说不方便。

2、Python 命令行参数获取

参考学习文章:
编写带命令行参数的Python程序
在Python有两种方式获取和分析命令行参数,
一是sys.argv,可以访问所有命令行参数列表

import sys
print 'Number of arguments:', len(sys.argv)
print 'They are:', str(sys.argv)```
运行:

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 就表示该选项无参数,i:表示 i 选项后需要有参数
    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:])

相关文章

网友评论

    本文标题:Python 简单应用

    本文链接:https://www.haomeiwen.com/subject/dwnozttx.html