美文网首页
Python传参模块简介

Python传参模块简介

作者: 小潤澤 | 来源:发表于2020-03-26 12:29 被阅读0次

getopt模块

这个模块的风格是将参数写到一个列表里面
这是它的语法

getopt.getopt(args, shortopts, longopts = [])

短选项模式

简单理解就是短模式就是有一个横杠的
我们看一个例子

import getopt

args = "-a -b -cfoo -d bar a1 a2".split()

我们将args打印出来可以发现,我们把它做成个以空格为分隔的list



接着写入

optlist,args = getopt.getopt(args,'abc:d:')
optlist
采用getopt()函数,将list做成list套tuple形式,对应着一个参数对应一个值
并且,a,b,c,d各对应唯一值(可以对应空值),所以optlist,args = getopt.getopt(args,'abc:d:')语句中后面的args自动分配a1,a2作为参数
args

长选项模式

简单理解,长模式就是有两个横杠的

import getopt

s = "--condition=foo --testing --output-file abc.def -a foo -x a1 a2" 
args = s.split()

一样的,做成以空格分隔的list
接着写入

optlist,args = getopt.getopt(args,'xa:',['condition=','output-file=','testing'])
optlist

其中optlist,args = getopt.getopt(args,'xa:',['condition=','output-file=','testing'])中xa:管的是短模式,中括号里面管的是长模式
然后剩下的a1,a2分配为参数


args

例子

import sys
import getopt


def usage():
    print("Usage: text.py -h help -p port -u URL")

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hp:u', ['help', 'port=', 'url='])

    except getopt.GetoptError as err: ##错误排障
        print(str(err))
        usage()
        sys.exit(0)

    for o, a in opts:  循环遍历参数
        if o in ('-h', '--help'):
            usage()
            sys.exit(0)
        elif o in ('-p', '--port'):
            print("PORT")
        elif o in ('-u', '--url'):
            print("URL")

if __name__ == "__main__":
        main()

argparse

个人感觉这个好用些,直接传参定义即可

import argparse
import os.path

parser = argparse.ArgumentParser()
parser.add_argument('-fa',action='store_true', dest='fasta',default=False, help='Check out the sequance')
parser.add_argument('-nt',action='store_true', dest='ntCounts',default=False, help='Calculate Nucleotide count')
parser.add_argument('-gc',action='store_true', dest='gcContent',default=False, help='Calculate gc content ')
parser.add_argument('-r', action='store_true', dest='rnaSeq', default=False, help='Calculate Transcription sequence')

parser.add_argument('-i',dest='filename',type=argparse.FileType('r'),help='Input file') #读取文件
args = parser.parse_args()

#参数传递
args.filename  //args+你的参数名

#涉及到多参数调用,打印对应结果,则添加if/if not即可,这样就可以打印你选择的参数结果,而不是全部都打印
if args.ntCounts and not args.gcContent and not args.rnaSeq and not args.fasta:
      print('Nucleotide count(A,C,G,T): ',ntCounts)
if not args.ntCounts and args.gcContent and not args.rnaSeq and not args.fasta:
      print('gc content: ',gcContent)
if not args.ntCounts and not args.gcContent and args.rnaSeq and not args.fasta:
      print('Transcription sequence: ',rnaSeq)
#若需要加print条目,则写在if里面(if/and not)
if not args.ntCounts and not args.gcContent and not args.rnaSeq and args.fasta:
    print('Sequence: ', fasta)

选择参数加if那些即可,这样我只选一个参数,那么就只执行这个参数的内容
否则会报错
或者

 parser = argparse.ArgumentParser(description="To caculate the phastcons value.")
 parser.add_argument("-a", "--a", required=True, type=str,help="the alignome directory")
 parser.add_argument("-b", "--b", required=True, type=str,help="the tree directory")
 parser.add_argument("-c", "--c", required=True, type=str,help="the goal numbers")
 parser.add_argument("-d", "--d", required=True, type=str,help="the output directory.")
 Args = parser.parse_args()

其中type定义传参数据类型

参考:https://www.jianshu.com/p/6f7078058023

http://docs.python.org/2.7/library/getopt.html#module-getopt

http://docs.python.org/2.7/library/argparse.html#module-argparse

http://www.cnblogs.com/lovemo1314/archive/2012/10/16/2725589.html

相关文章

网友评论

      本文标题:Python传参模块简介

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