-2

My function convert.py is:

def convert(a,b)
  factor = 2194.2
  return (a-b)*factor

How do I run it from the command line with input arguments a and b?
I tried:

python convert.py 32 46

But got an error.

I did try to find the answer online, and I found related things but not the answer:

  1. Run function from the command line (Stack Overflow)
  2. How to read/process command line arguments? (Stack Overflow)
  3. http://www.cyberciti.biz/faq/python-command-line-arguments-argv-example/
  4. http://www.saltycrane.com/blog/2007/12/how-to-pass-command-line-arguments-to/

Also, where can I find the answer myself so that I can save this site for more non-trivial questions?

Nike
  • 1,223
  • 2
  • 19
  • 42

2 Answers2

0

There exists a Python module for this sort of thing called argparse, which allows you to do really fancy things around command line flags. You don't really need that - you've just got two numbers on the command line. This can be handled really naively.

Python allows you direct access to the command line arguments via an array called sys.argv - you'll need to import sys first. The first element in this array is always the program name, but the second and third will be the numbers you pass in i.e. sys.argv[1] and sys.argv[2]. For a more complete example:

if len(sys.argv) < 3:
    print 'Didnt supply to numbers'
a = int(sys.argv[1])
b = int(sys.argv[2])

Of course you'll need some error checking around making sure they are actuall integers/floats.

A bit of extra reading around sys.argv if you're interested here

To be complete, we can give an argparse example as well:

import argparse

parser = argparse.ArgumentParser(description='')
parser.add_argument('numbers', type=float, nargs=2,
                            help='Things to perform actions on')
args = parser.parse_args()

a = args.numbers[0]
b = args.numbers[1]

print a, b
Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45
0

You could do:

import sys
def convert(a,b):
    factor = 2194.2
    return (a-b)*factor
print(convert(int(sys.argv[1]), int(sys.argv[2])))

If that is all what should do the script, you dont have to define a function:

import sys
factor = 2194.2
print((int(sys.argv[1]), int(sys.argv[2])*factor)

If you don't want to change your file (aside from the fact that you have to add the colon after the function definition), you could follow your first linked approach:

python -c 'import convert, sys; print convert.convert(int(sys.argv[1]), int(sys.argv[2])'
Community
  • 1
  • 1
petres
  • 582
  • 2
  • 19