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):
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. , , .