如何使用 argparse 模块在 python 脚本中将文件作为参数传递?

how to pass file as argument in python script using argparse module?

我正在使用 argparse 模块在 python 中编写一个自动化脚本,我想在其中使用 -s 作为一个选项,该选项将 file/file 路径作为参数。有人可以帮我做这个吗?

示例:./argtest.py -s /home/test/hello.txt

只需这样做:

import argparse

parser = argparse.ArgumentParser(description="My program!", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-s", type=argparse.FileType('r'), help="Filename to be passed")
args = vars(parser.parse_args())

open_file = args.s

如果要打开文件进行写入,只需在type=argparse.FileType('r')中将r更改为w即可。您也可以将其更改为 ar+w+

您可以使用

import argparse

parse = argparse.ArgumentParser()
parse.add_argument("-s")
args = parse.parse_args()
# print argument of -s
print('argument: ',args.s)

假设上面的代码存储在文件example.py

$ python example.py -s /home/test/hello.txt
argument: /home/test/hello.txt

您可以点击here(Python3.x) or here(Python2.x)了解更多。