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?
1
Few things to note down are:-
-
Calling import inside a function in Python is however generally not recommended as importing modules is a relatively expensive operation.
-
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
0
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
0
Just for future readers, I write here down the code that worked for me.
This code employes the solutions of @Prateekshit Jaiswal and @OldBoy, who I thank a lot!
def MultiplicateLists(a):
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)
if __name__ == "__main__":
import sys
import numpy as np
input_list = list(map(int, sys.argv[1].strip('[]').split(',')))
a = np.array(input_list)
MultiplicateLists(a)
Then, in the terminal, I type the following:
% python3 MyFunction.py 1,3,5,6,4,6,7,1,2,7
And I get this result:
[1 3 5 6 4 6 7 1 2 7]
[7 4 6 9 6 4 5 7 7 6]
[ 7 12 30 54 24 24 35 7 14 42]
1