簡體   English   中英

Python腳本從shell接受多個參數

[英]Python script to take multiple number of arguments from shell

我正在嘗試從終端獲取多個文件作為輸入。 輸入的數字可能從至少1到很多不等。 這是我程序的輸入

F3.py -e <Energy cutoff> -i <inputfiles>

我希望參數-i接受從1到Multiple.eg的任意數量的值。

F3.py -e <Energy cutoff> -i file1 file2
F3.py -e <Energy cutoff> -i *.pdb

現在,它僅獲取第一個文件,然后停止。 這是我到目前為止的內容:

def main(argv):
try:
    opts,args=getopt.getopt(argv,"he:i:")
    for opt,arg in opts:
        if opt=="-h":
            print 'F3.py -e <Energy cutoff> -i <inputfiles>'
            sys.exit()
        elif opt == "-e":
            E_Cut=float(arg)
            print 'minimum energy=',E_Cut
        elif opt == "-i":
            files.append(arg)
            print files
    funtction(files)
except getopt.GetoptError:
    print 'F3.py -e <Energy cutoff> -i <inputfiles>'
    sys.exit(2)

任何幫助,將不勝感激。 謝謝

嘗試使用@larsks建議,下一個代碼片段應適用於您的用例:

import argparse 

parser = argparse.ArgumentParser()

parser.add_argument('-i', '--input', help='Input values', nargs='+', required=True)

args = parser.parse_args()

print args

kwargs的解釋:

  • nargs允許您將值解析為列表,因此您可以使用類似的方法進行迭代: for i in args.input
  • required使該參數成為required參數,因此您必須添加至少一個元素

通過使用argparse模塊,您還獲得了-h選項來描述您的參數。 因此,請嘗試使用:

$ python P3.py -h
usage: a.py [-h] -i INPUT [INPUT ...]

optional arguments:
  -h, --help            show this help message and exit
  -i INPUT [INPUT ...], --input INPUT [INPUT ...]
                        Input values


$ python P3.py -i file1 file2 filen
Namespace(input=['file1', 'file2', 'filen'])

如果您堅持使用getopt ,則必須將多個參數與除空格之類的分隔符組合使用,然后像這樣相應地修改代碼

import getopt
import sys

try:
    opts,args=getopt.getopt(sys.argv[1:],"he:i:")
    for opt,arg in opts:
        if opt=="-h":
            print 'F3.py -e <Energy cutoff> -i <inputfiles>'
            sys.exit()
        elif opt == "-e":
            E_Cut=float(arg)
            print 'minimum energy=',E_Cut
        elif opt == "-i":
            files = arg.split(",")
            print files
    #funtction(files)
except getopt.GetoptError:
    print 'F3.py -e <Energy cutoff> -i <inputfiles>'
    sys.exit(2)

運行此命令時,您將獲得輸出

>main.py -e 20 -i file1,file2
minimum energy= 20.0
['file1', 'file2']

注意我已經注釋了您的函數調用,並從主函數中取消了將代碼包裝的內容,您可以在代碼中重做這些事情,這不會改變您的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM