簡體   English   中英

Arg解析:將文件名解析為字符串(python)

[英]Arg parse: parse file name as string (python)

我想將文件名解析為字符串形式的腳本,而不是直接將文件轉換為對象。

這是一個示例代碼test.py

import argparse
import os.path
def is_valid_file(parser, arg):
      if not os.path.exists(arg):
           parser.error("The file %s does not exist! Use the --help flag for input options." % arg)
      else:
           return open(arg, 'r')

parser = argparse.ArgumentParser(description='test') 
parser.add_argument("-test", dest="testfile", required=True,
                    help="test", type=lambda x: is_valid_file(parser, x))
args = parser.parse_args()    
print args.testfile

testfile是一個.txt文件,其中包含: 1,2,3,4

原則上,希望print args.testfile以字符串形式返回testfile的調用名稱:

$ python test.py -test test.txt
>> "test.txt"

為此,我需要防止argparser將test.txt轉換為對象。 我怎樣才能做到這一點?

非常感謝!

您可以按如下所示修改函數,以在檢查字符串存在后返回該字符串:

def is_valid_file(parser, arg):
      if not os.path.exists(arg):
           parser.error("The file %s does not exist! Use the --help flag for input options." % arg)
      else:
           return arg

還有一種更直接的方法:

parser.add_argument("-test", dest="testfile", required=True,
                    help="test", type=file)  # file exists in python 2.x only

parser.add_argument("-test", dest="testfile", required=True,
                    help="test", type=lambda f: open(f))  # python 3.x

args = parser.parse_args()    
print(args.testfile.name)  # name of the file from the file handle

實際上args.testfile是由argparser打開的文件句柄(如果找不到,則為例外)。 您可以直接閱讀。

FileType類型工廠執行代碼的大部分工作,但消息機制略有不同:

In [16]: parser=argparse.ArgumentParser()
In [17]: parser.add_argument('-f',type=argparse.FileType('r'))

In [18]: args=parser.parse_args(['-f','test.txt'])
In [19]: args
Out[19]: Namespace(f=<_io.TextIOWrapper name='test.txt' mode='r' encoding='UTF-8'>)
In [20]: args.f.read()
Out[20]: '  0.000000,  3.333333,  6.666667, 10.000000, 13.333333, 16.666667, 20.000000, 23.333333, 26.666667, 30.000000\n'
In [21]: args.f.close()

對於有效名稱,它將打開文件,您可以使用它並關閉它。 但是您不能在with上下文中使用它。

如果該文件不存在,它將退出並顯示使用情況和cant open消息。

In [22]: args=parser.parse_args(['-f','test11.txt'])
usage: ipython3 [-h] [-f F]
ipython3: error: argument -f: can't open 'test11.txt': [Errno 2] No such file or directory: 'test11.txt'

FileType __call__使用argparse.ArgumentTypeError處理錯誤

   except OSError as e:
        message = _("can't open '%s': %s")
        raise ArgumentTypeError(message % (string, e))

使用此錯誤機制,並省略您的open提示:

def valid_file(astring):
    if not os.path.exists(astring):
        msg = "The file %s does not exist! Use the --help flag for input options." % astring
        raise argparse.ArgumentTypeError(msg)
    else:
        return astring

可以用作:

In [32]: parser=argparse.ArgumentParser()
In [33]: parser.add_argument('-f',type=valid_file)

In [34]: args=parser.parse_args(['-f','test11.txt'])
usage: ipython3 [-h] [-f F]
ipython3: error: argument -f: The file test11.txt does not exist! Use the --help flag for input options.
An exception has occurred, use %tb to see the full traceback.

SystemExit: 2

In [35]: args=parser.parse_args(['-f','test.txt'])
In [36]: args
Out[36]: Namespace(f='test.txt')
In [37]: with open(args.f) as f:print(f.read())
  0.000000,  3.333333,  6.666667, 10.000000, 13.333333, 16.666667, 20.000000, 23.333333, 26.666667, 30.000000

http://bugs.python.org/issue13824擔心FileType打開文件而不關閉文件。 我提出了一個以FileType為模型的FileContext ,但是沒有打開文件,而是返回了一個可用作以下對象的對象:

with arg.file() as f:
    f.read()

它將執行文件存在性或可創建性測試,而無需實際打開或創建文件。 這是一個更復雜的解決方案。

暫無
暫無

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

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