में वैकल्पिक वैकल्पिक बनाने के लिए कैसे मैं अपने प्रोजेक्ट के इन आमंत्रणों को बनाना चाहता हूं, और कोई अन्य नहीं।python argparse
$ python3 myprog.py -i infile -o outfile
$ python3 myprog.py -o outfile
$ python3 myprog.py -o
$ python3 myprog.py
विशेष रूप से मैं इसे अविनाशी निर्दिष्ट करने के लिए अवैध बनाना चाहता हूं लेकिन आउटफाइल नहीं।
तीसरे मामले में, आउटफाइल के लिए एक डिफ़ॉल्ट नाम माना जाता है, "out.json।" दूसरे, तीसरे और चौथे मामलों में, इनपुट फ़ाइल के लिए एक डिफ़ॉल्ट नाम माना जाता है, "file.n.json", जहां n एक पूर्णांक संस्करण संख्या है। चौथे मामले में आउटपुट फ़ाइल "file.n + 1.json" होगी जहां n + 1 इनपुट फ़ाइल पर एक से बड़ा संस्करण संस्करण है। मेरी कोड के प्रासंगिक अनुभाग है:
import argparse
parser = argparse.ArgumentParser(description="first python version")
parser.add_argument('-i', '--infile', nargs=1, type=argparse.FileType('r'), help='input file, in JSON format')
parser.add_argument('-o', '--outfile', nargs='?', type=argparse.FileType('w'), default='out.json', help='output file, in JSON format')
args = parser.parse_args()
print("Here's what we saw on the command line: ")
print("args.infile",args.infile)
print("args.outfile",args.outfile)
if args.infile and not args.outfile:
parser.error("dont specify an infile without specifying an outfile")
elif not args.infile:
print("fetching infile")
else: # neither was specified on the command line
print("fetching both infile and outfile")
समस्या है, जब मैं
$ python3 myprog.py -i infile.json
बजाय पार्सर त्रुटि मैं के लिए आशा व्यक्त की चलाते हैं, तो मैं मिलता है:
Here's what we saw on the command line:
args.infile [<_io.TextIOWrapper name='infile.json' mode='r' encoding='UTF-8'>]
args.outfile <_io.TextIOWrapper name='out.json' mode='w' encoding='UTF-8'>
fetching both infile and outfile
... जो बताता है कि यद्यपि कमांड लाइन पर "-o" नहीं था, फिर भी ऐसा लगता था कि वहां था।
तीसरे और चौथे मामले के बीच क्या अंतर है? क्या खड़ा है? –
चौथा मामला डिफ़ॉल्ट इन्फाइल और आउटफाइल नामों का उपयोग करेगा (विशेष रूप से file.n.json और file.n + 1.json, यानी संस्करण संख्या वाले संस्करणों के साथ)। ये "out.json" से अलग हैं जो "-o" विकल्प के साथ तीसरा मामला होगा। मैंने इसे इंगित करने के लिए ऊपर दिए गए पाठ को संशोधित किया है। – user1416227
चौथा मामला '- इनपुट' विकल्प के रूप में काम करने के लिए कैसे डिफ़ॉल्ट है? – maxschlepzig