1

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.

Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
Jamulive
  • 121
  • 4
  • 1
    Hope, this might help. http://stackoverflow.com/questions/7033987/python-get-files-from-command-line – ravindar Jun 10 '16 at 08:12

1 Answers1

2

The simplest way is with the sys library. Arguments to the python interpreter are stored in 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 library

import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('filepath')
    args = parser.parse_args()
    print args.filepath
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118