1

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?

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

5 Comments

OK, I got that to run, but how do I use command line arguments in place of hard coding the arguments, as in test('testing')? Basically I want a function that I can invoke with command line arguments.
OK, even shorter: #----testit.py---- def test(arg): print ("arg" + arg) run it by: python testit.py test("TEST") but I get nothing. How do I get "arg" + the arg to print out???? This seems to totally basic and yet after looking and looking I find nothing.
SORRY FOR THE BAD FORMATTING!
def test(arg): print ("arg" + arg) And I run it: python test.py test("123") or python test.py test "123" Nothing happens; no error, just nothing prints out.
HI. Apologies!!! I was just unused to the Python syntax; defining a function and then sort of calling it in the same file. I made my search and replace Python program (not mine; I got it on Stackoverflow.com) work just fine.
2

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

5 Comments

BUT, but, how does Python find test? I mean, if it's in a file named, say, random.py, and I run random.py...? In the cast of test( ), or test.py, how can I print out command line arguments? I'm still rather unclear. I understand def means define, etc. If I removed the line test('my args') which hard codes the arguments, and try to run test.py "args" I get "HERE" but nothing else.
You are talking about something completely different. Take a look at this article for more information docs.python.org/dev/library/argparse.html
Really, all I want is to run a script from the command line. I'm not sure why it's such a pain, one that accesses the command line parameters. This is like day one in C,C++ and C#, and Java. Totally built in and trivial yet...it seems very awkward here. What I want to do is get/write a script that will do mass search and replace in many files in a folder.
It's actually pretty simple and I prefer the way it is done in Python. I added an example @ron
btw you should be much clearer in your future questions at stackoverflow, because it was not mentioned at all in your question that you were looking for a way to execute a script through the command line script with specific arguments.
1

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()

Comments

1

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)

2 Comments

print ("HERE") def test(arg): print ("arg" + arg) That's the file (those three lines). Does it matter what I call it? I just want to invoke test( arg) that's all. Seems simple.
I've looked on line for processing command line parameters with Python. Maybe it's not meant for that and it's sort of a kluge to do it? Is that it? I mean, this is trivial for C, C++, C# and Java and yet on line all I find are rather complex examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.