TrackLab
TrackLab

Reputation: 32

Python Programm, how to use console input on file execution?

Let´s say I execute a python file like a program in Ubuntu

python filename.py --input1 --input2

How can I use those 2 inputs in my code? (If even possible with python)

BTW I would like to do this on Windows, not Linux. For example, my code contains a function that takes 1 argument, in form of a string.

I could just do that argument input as input() while the code is running, but I would like to specify it when I execute the code already.

Upvotes: 0

Views: 824

Answers (3)

eapetcho
eapetcho

Reputation: 527

For a simple case, you can just use sys.argv as follows:

# in your source.py
from sys import argv

arg1 = argv[1] # If your input is a "numerci type" , apply the the appropriate
arg2 = argv[2] # conversion by using (int, float)

...

Then you can execute your code, by:

python source.py arg1 arg2

Upvotes: 0

teroi
teroi

Reputation: 1087

This is certainly possible and in fact even bread and butter in python and other script languages.

In python there is even the getopt module that helps you with that if you are familiar with the c implementation.

Copy-paste from official python documentation: import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-o", "--output"):
            output = a
        else:
            assert False, "unhandled option"
    # ...

if __name__ == "__main__":
    main()

Official documentation is here: https://docs.python.org/2/library/getopt.html

For tutorials, see for example: https://www.tutorialspoint.com/python/python_command_line_arguments.htm

On the other hand argparse is easier if you like to get it done in an easier but not c-like way. For that, see the other answer.

Upvotes: 1

Dave N
Dave N

Reputation: 113

I recommend you take a look at argparse. https://docs.python.org/3.7/howto/argparse.html

Or

$ python
>>> import argparse
>>> help(argparse)

Upvotes: 1

Related Questions