Error handling when waiting for an argument

The first message, also the first attempt to encode something beyond 99 bottles ...

I am working on code that takes an argument from cli, such as a text file. Expected Use:

$: myfile.py input.txt

I have this thing that runs smoothly, but if no argument is given, cli returns an error, and I would like to provide some error response, such as a help list or just "No" - give me the file "

Here are the first few lines:

import sys
with open(sys.argv[1], 'r') as f:
    ifile = f.read()
    if len(sys.argv) == 1:
        empty = "Please give me something to do!"
        print empty

If I put the expected argument, everything will be fine, but if the argument is not specified, I get the following:

Traceback (most recent call last):
  File "myfile.py", line 3, in <module>
    with open(sys.argv[1], 'r') as f:
IndexError: list index out of range

Suppose I just want the "Empty" variable to be printed if the condition is not met ... what would I do to fix it.

edit: , argparse, , , argparse , . :

   def main(filename):
    # do something with filename
    print('your filename is %s' % filename)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='my program help')
    parser.add_argument('-f', help='specify file path')

, -h -f , F .

my program help

optional arguments:
  -h, --help  show this help message and exit
  -f F        specify macro file path

, F. , , .

+4
3

argparse cli:

:

import argparse


def main(filename):
    # do something with filename
    print('your filename is %s' % filename)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='my program help')
    parser.add_argument('filename', help='your desired filename')

    args = parser.parse_args()
    main(args.filename)

, :

$ python ans_argparse.py
usage: ans_argparse.py [-h] filename
ans_argparse.py: error: the following arguments are required: filename

:

$ python ans_argparse.py 'myfile.txt'
your filename is 'myfile.txt'

. argparse stdlib, .

parse_args(), __main__ :

import sys
import argparse


def main(filename):
    # do something with filename
    print('your filename is %s' % filename)


def parse_args(args_lst):
    parser = argparse.ArgumentParser(description='my program help')
    parser.add_argument('filename', help='your desired filename')
    return parser.parse_args(args_lst)


if __name__ == '__main__':
    args = parse_args(sys.argv[1:])                 
    main(args.filename)

:

args = parse_args(['another_filename.txt'])

Update

metavar . argparse

:

parser.add_argument('-f', metavar='FILENAME', required=True, 
                    help='the file path for this program')

python myprog.py --help:

optional arguments:
  -h, --help   show this help message and exit
  -f FILENAME  the file path for this program

note: required=True, argparse.

+3

sys.argv, - , , .

,

import sys
if len(sys.argv)>1:
    #do something
else:
    print "Please give me something to do!"
0

argparse great, but you can also keep it simple

import sys

if len(sys.argv) != 2:
    sys.stderr.write("Usage: myfile.py textfile\n")
    exit(1)

with open(sys.argv[1], 'r') as f:
    pass # ...
-1
source

Source: https://habr.com/ru/post/1667904/


All Articles