How to apply a python file execution over selected file in OSX Terminal?
Question: I am asked to create a python file abc.py, and then execute that python
command over filename.txt

The code in terminal (OSX):

    
    
        $ python abc.py filename.txt
    

How do I write the code in the abc.py file such that it is will read
"filename.txt" from the command-line, as an input in the python code?

Thanks much.


Answer: The simplest way is with the `sys` library. Arguments to the python
interpreter are stored in
[`sys.argv`](https://docs.python.org/2/library/sys.html#sys.argv)

    
    
    import sys
    
    
    def main():
        # sys.arv[0] is the path to this script (ie. /path/to/abc.py)
        filepath = sys.argv[1]
        print filepath
    
    
    if __name__ == '__main__':
        main()
    

If you wanted to get fancier, you could use the
[`argparse`](https://docs.python.org/2/library/argparse.html) library

    
    
    import argparse
    
    def main():
        parser = argparse.ArgumentParser()
        parser.add_argument('filepath')
        args = parser.parse_args()
        print args.filepath
    

