skip to Main Content
def add(a,b):
    return a+b

I made python function at vsc and I want to execute that function in terminal like

add(2,3)

But if so there is an error like bash: syntax error near unexpected token `2,3′
I think the matter of path of terminal but I do not know what to do

I have tried something related to path of terminal but IDK what is matter

2

Answers


  1. You need to save the file with the function, then run the function through the command line using python3 -c

    I created a file sample.py with your function

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

    and I ran the following command from the command-line terminal.

    python3 -c 'from sample import add; print(add(2,3))'
    

    and the output was

    5
    

    Note that, I am using Linux, that’s why it is python3, for windows, you need to use python only.

    Login or Signup to reply.
  2. If you want to run your function from the command line a lot, it may be cleanest to make it an executable script. On Linux:

    #!/usr/bin/python3 
    
    from sys import argv
    
    
    def add(a, b):
        return a + b
    
    
    if __name__ == '__main__':
        print(add(int(argv[1]), int(argv[2])))
    

    Make sure the script is executable:

    chmod +x add.py
    

    Now you can run it from the terminal:

    ./add.py 2 3
    5
    

    If you are going to make it more complex, I recommend checking out argparse. It’s more powerful than argv.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search