嗨,大家好,我是編程和Python新手。我尋找我的問題的答案,但我無法找到它。如何在Python中跳過位置參數Argparse
我使用Argparse爲我的腳本解析參數。現在我想編寫一個運行特定工具的程序,如果第一個參數(程序名稱後面)是工具的名稱(在類中關閉)。例如,如果我想運行「計數器」工具,我必須鍵入:
python myscript.py counter filename
而如果我想運行「fasta2bed」我必須鍵入:
python myscript.py fasta2bed filename
我寫了這個代碼,但好像你不能跳過的位置參數與Argparse:
import argparse
parser=argparse.ArgumentParser(
usage="""python myscript.py {toolname} filename [-option]""",
description='''Description.''',
epilog="""Epilog.""")
parser.add_argument('counter', nargs='?', choices=['counter'], help='count how many features are in the input file [-l][-s]')
parser.add_argument('fasta2bed', nargs='?', choices=['fasta2bed'], help='read sequences in FASTA format and print out BED format')
parser.add_argument('filename', help='the input file name')
parser.add_argument('-l', '--long', action='store_true', help='retrive a long summary file (default)')
parser.add_argument('-s', '--short', action='store_true', help='retrive a short summary file')
args=parser.parse_args()
的問題是,當我嘗試運行python myscript.py fasta2bed文件名這是行不通的,因爲它需要計數器。
所以我嘗試插入所有在這樣一個參數:
parser.add_argument('tool', nargs='?', choices=['counter', 'fasta2bed'], help='help')
這個目的:
data = open("inputfile", "r")
if args.tool == "counter":
counter(data).summarize() #summarize is a function present in the counter class
elif args.tool == "fasta2bed":
fasta2bed(data) #fasta2bed is just a function
,但因爲它運行fasta2bed的櫃檯,而不是它不工作.. 。
有沒有辦法達到這個目標?也許沒有argparse?
非常感謝您的時間!
沒有你看看docopt(https://github.com/docopt/docopt)更容易使用 – Salo
我認爲這將是非常有用的,非常感謝你! – Revo