2014-02-05 49 views
4

嗨我想從命令行使用argparse輸入文件名,但我努力讓它工作。使用argparse來輸入文件名

我想從命令行(-d)傳遞一個對應於文件名(datbase.csv)的字符串,並將其存儲在變量inputargs.snp_database_location中。

這將作爲我的load_search_snaps函數的輸入,如下面的代碼所示,它打開文件並對它執行一些操作(僞代碼)。

import csv, sys, argparse 

    parser = argparse.ArgumentParser(description='Search a list of variants against the in house database') 
    parser.add_argument('-d', '--database', 
     action='store', 
     dest='snp_database_location', 
     type=str, 
     nargs=1, 
     help='File location for the in house variant database', 
     default='Error: Database location must be specified') 

    inputargs = parser.parse_args() 

    def load_search_snps(input_file): 
     with open(input_file, 'r+') as varin: 
      id_store_dictgroup = csv.DictReader(varin) 
      #do things with id_store_dictgroup                   
     return result 

    load_search_snps(inputargs.snp_database_location) 

使用在bash命令:

python3 snp_freq_V1-0_export.py -d snpstocheck.csv

我收到以下錯誤,當我嘗試從同一目錄傳遞一個普通的CSV文件中使用的命令行:

File "snp_freq_V1-0_export.py", line 33, in load_search_snps with open(input_file, 'r+') as varin: TypeError: invalid file: ['snpstocheck.csv']

如果我從腳本內部提供文件路徑,它可以很好地工作。據我可以告訴我得到一個匹配文件名字符串的snp_database_location的字符串,但後來我得到了錯誤。我錯過了什麼是給類型錯誤?

+0

您在錯誤消息中缺少'[]'。列表和字符串之間的區別很重要。 – hpaulj

回答

4

nargs=1使得inputargs.snp_database_location列表(有一個元素),而不是一個字符串。

In [49]: import argparse 

In [50]: parser = argparse.ArgumentParser() 

In [51]: parser.add_argument('-d', nargs=1) 
Out[51]: _StoreAction(option_strings=['-d'], dest='d', nargs=1, const=None, default=None, type=None, choices=None, help=None, metavar=None) 

In [52]: args = parser.parse_args(['-d', 'snpstocheck.csv']) 

In [53]: args.d 
Out[53]: ['snpstocheck.csv'] 

要修復,請刪除nargs=1

+0

太棒了,非常感謝! SB :) –

相關問題