I have
file1 = sys.argv[1]
file2 = sys.argv[2]
file2 = sys.argv[3]
How can I put this in 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.
Prints the following when you use the --help
command-line switch:
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.