How can I run a python code with input on Linux terminal?

Question:

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.

Asked By: Albert

||

Answers:

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.

Answered By: Code-Apprentice

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']
Answered By: Alvaro Cuervo

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
Answered By: Raj Josyula

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

Answered By: Dan D.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.