Ron
Ron

Reputation: 2503

Invoking function using command args

I have the following code.

import os, fnmatch, sys
print ("HERE")
def test(arg):
    print ("arg" + arg)

How would I go about invoking the function test when running the script from the command line?

Upvotes: 1

Views: 379

Answers (5)

eandersson
eandersson

Reputation: 26362

The simplest way to get the command line options in Python is using sys.argv. This stores any command line options for you in the form of an array.

Printing the arguments is super simple.

import sys
print(str(sys.argv))

If you would run the following command line on this script: python test.py arg1 arg2 arg3 It would print ['test.py', 'arg1', 'arg2', 'arg3']

You can use this to build invoke your function. But, as you may have noticed with our output is that it does not only contain your arguments, but also the name of the file that we executed. Because of this we need to first make sure that the user provided us with at least one argument, besides the filename.

We do this using len.

import sys
if len(sys.argv) > 1:
   print(sys.argv[1])

We could then use this with your function to print the first argument.

import sys
def test(arg):
   print ("arg" + arg)
if len(sys.argv) > 1:
   test(sys.argv[1])

If you want to run invoke the function test from the command line you preferably would use something like the OptionParser to parse the args. Although, keep in mind that OptionParser has been deprecated, and you should consider using ArgParse instead.

This is a working example using the OptionParser and your function.

from optparse import OptionParser

# Options/Args
parser = OptionParser()

# Add Options
parser.add_option("-t", "--test", dest="test")

# Parse the Options
(options, args) = parser.parse_args()
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)

print ("HERE")
def test(arg):
    print ("arg: " + arg)

# If the command line for test was specified.
if options.test:
    # Run the test function.
    test(options.test)

When you run the application you simply add -t your-text to invoke your function.

e.g. python3 test.py -t hello

Would output:

HERE
arg: hello

Upvotes: 2

Morten Jensen
Morten Jensen

Reputation: 5946

This python idiom is used a lot too:

if __name__ == "__main__":
    # do stuff
    ...

Everything inside this if-clause will run when the script is run from the console. That way you can put driver code in module files etc.

If you replaced the ... above with test("blah blah") you'd get the results you want :)

Upvotes: 3

frickskit
frickskit

Reputation: 624

under

def test(arg):
    print ("arg" + arg)

write

test('testing')

then run it the same way you did before. To run it with user input,

uinpt = raw_input("Enter something: ")
test(uinpt)

Upvotes: 1

suffa
suffa

Reputation: 3806

Here is a very simple example w/ no argument:

def do_hex():
text=raw_input("Enter string to convert to hexadecimal: ")
print "HEX: " + text.encode('hex')

#call the function

do_hex()

Upvotes: 1

hpalaiya
hpalaiya

Reputation: 21

The def construct in Python is short for 'define'. The code block you've written defines the test function but does not call it. After defining the test function in the interpreter, you can execute the command

test('whatever') 

with 'whatever' being anything you want. Or you can put that command in your file after defining test and then enter test.py

Upvotes: 2

Related Questions