1

I have a file named myadd.py that contains only the following function:

def myadd(a,b):
    return a+b

How can I run it on Linux terminal? I am looking for something easy like this:

python myadd 2,3

My final goal is to send multiple jobs to the server by making a .sh file containing:

bsub -J job1 python myadd 2,3
bsub -J job1 python myadd 4,5
bsub -J job1 python myadd 6,3
.
.
.
.

Let me know if I need to make any changes to be able to do something like the line above.

Nick T
  • 25,754
  • 12
  • 83
  • 121
Albert
  • 389
  • 3
  • 17

4 Answers4

4

You can use argparse

code:

import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-n", "--numbers", required=True, default=None, type=str,
    help="Input your numbers to add separated by comma")

args = vars(ap.parse_args())

numbers = args["numbers"].split(",") # Parse the arguments
numbers = [int(i) for i in numbers] # convert from str to int list

def addition(a: int, b: int):
    """Add function"""
    return a+b

print("Result: {}".format(addition(numbers[0], numbers[1])))

Usage:

(pyenv)  ✘ rjosyula  ~  python x.py --help
usage: x.py [-h] -n NUMBERS

optional arguments:
  -h, --help            show this help message and exit
  -n NUMBERS, --numbers NUMBERS
                        Input your numbers to add separated by comma

Results in

python x.py --numbers 2,3
Result: 5
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Raj Josyula
  • 140
  • 1
  • 12
2

You need to use sys.argv to accept command line arguments. I suggesting using a space between the two numbers instead of a comma. For more details, see sys.argv[1] meaning in script and the official documentation. If you need more complex command line arguments, I suggest you check out the argparse library.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
2

Also the fire module.

This only needs:

import fire

def myadd(a, b):
    return a+b

if __name__ == '__main__':
    fire.Fire(myadd)

The import guard was edited in. It isn't needed here as the script is unlikely to be used as a module. I intentional left it out due to that.

To result in a command

python script.py 1 2

That prints 3

Dan D.
  • 73,243
  • 15
  • 104
  • 123
1

You need to use command line arguments.

For example, in the following code:

import sys

print ('# Args:', len(sys.argv))
print ('Argument List:', str(sys.argv))

If you call it from the terminal...

python3 test_args.py ar1 ar2 ar3 ar4 ar5

Gives as a result:

# Args:: 6
Argument List: ['test_args.py', 'ar1', 'ar2', 'ar3', 'ar4', 'ar5']