skip to Main Content

I would like to import a list in a python function and run the function from the terminal of Visual Studio Code. My function, that I called "MyFunction.py", and that I temporarily saved on the Desktop, is the following one:

def MultiplicateLists(a):
    import numpy as np
    import random
    rand_list=[]
    for i in range(10):
        rand_list.append(random.randint(3,9))
    b = np.array(rand_list)
    result = a * b
    print(a)
    print(b)
    print(result)

However, when I try to call and make the function run from the terminal of Visual Studio Code, I get the following error, i.e. "zsh: no matches found":

(anaconda3) (base) xxxyyyzzz@xxx Desktop % python3 MyFunction.py MultiplicateLists(np.array([1,3,5,6,4,6,7,1,2,7]))
zsh: no matches found: MultiplicateLists(np.array([1,3,5,6,4,6,7,1,2,7]))

Here following a screenshot from Visual Studio Code

enter image description here

Might it be that the command "python3 MyFunction.py MultiplicateLists()" is wrong? How can I fix it?

2

Answers


  1. You cannot execute a Python program in that way. You need a main driver part which reads the inputs, creates an array, and passes them in to the MultiplicateLists function.
    So add the following to the end of your file:

    if __name__ == "__main__":
        numbers = []
        for x in map(int, sys.argv[1].split(',')):
            numbers.append(x)
    
        print(numbers)
        MultiplicateLists(np.array(numbers))
    

    You can now run the script by a command in the following form:

    python Myfunction.py 1,3,5,6,4,6,7,1,2,7
    
    Login or Signup to reply.
  2. Few things to note down are:-

    1. Calling import inside a function in Python is however generally not recommended as importing modules is a relatively expensive operation.

    2. What you are trying to do is passing argument to the file MyFunction.py which needs to be handled by the code itself as system arguments .Hence to call a function from a Python file from the terminal, you’ll need to modify your file to accept command-line arguments or to define a main function that calls your desired function.

      if __name__ == "__main__":
          input_list = list(map(int, sys.argv[1].strip('[]').split(',')))
          a = np.array(input_list)
          MultiplicateLists(a)
      

    Now You can easily call it by the following command:-

    python Myfunction.py 1,3,5,6,4,6,7,1,2,7
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search