Reputation: 45
I am newbie in python programming and need your help. I am running a python script using exec(open("./path to script/script.py").read()). If I try to pass a argument then I always get the error the file doesnt exists, somehow the interpreter assumes that the string passed is the file name which is obviously not correct.
>>> exec(open("./path to script/script.py" "hello").read())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: './path to script/script.pyhello'
Anybody has any tip on how to resolve this.
Thanks for your help.
Upvotes: 1
Views: 6577
Reputation: 813
Since you want to open a file and pass an argument as well, I'd advise you to use os.system()
from the os
module to achieve this as exec()
does not provide you with that kind of functionality as you can only pass a string into it.
Example:
Script.py:
arg = input()
print(arg)
Call to the above Script:
import os
os.system('python3 home/pathtoscript/script.py Hello')
This will print the desired output for you on the terminal. But it also depends on what you want to achieve further with it.
Output:
Hello
I'd also suggest using argparse
module for dealing with arguments as it provides great support if you are trying your hand at multiple arguments. Here is the official documentation for the same.
Good Luck and Happy Coding.
Upvotes: 1