[英]How to convert sys.argv to argparse in python
I have 我有
file1 = sys.argv[1]
file2 = sys.argv[2]
file2 = sys.argv[3]
How can I put this in argparse? 我怎么能把它放在argparse中?
Ready-opened file objects: 准备打开的文件对象:
import argparse, sys
parser = argparse.ArgumentParser(description='Process src to dst')
parser.add_argument('src', type=argparse.FileType('r'),
default=sys.stdin)
parser.add_argument('dst', type=argparse.FileType('w'),
default=sys.stdout)
options = parser.parse_args()
Then use options.src
and options.dst
as already-open file objects. 然后使用
options.src
和options.dst
作为已打开的文件对象。
Prints the following when you use the --help
command-line switch: 使用
--help
命令行开关时打印以下内容:
usage: somescript.py [-h] src dst
Process src to dst
positional arguments:
src
dst
optional arguments:
-h, --help show this help message and exit
If the FileType
in Martijn's answer confuses you, a more basic setup is 如果Martijn的答案中的
FileType
让您感到困惑,那么更基本的设置就是
import argparse
p=argparse.ArgumentParser()
p.add_argument('file1')
p.add_argument('file2')
p.add_argument('file3')
test with: 测试:
import sys
sys.argv.extend(['file1','file2','file3')
p.parse_args()
# Namespace(file1='file1', file2='file2', file3='file3')
Here you open the files yourself, whereas with FileType
, arpgparse
does that for you, and takes care of error messages if it has problems. 在这里,您可以自己打开文件,而使用
FileType
, arpgparse
会为您执行此操作,并在出现问题时处理错误消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.