I'm trying to execute file1.py from file2 .py by using exec function.
exec(open('file1.py').read())
Now I want to pass parameter target='target.yaml' to file1.py from exec function. How I can do that ?
Please help
You can use subprocess module:
file1:
import subprocess
print("Running file1.py")
subprocess.run("python file2.py target.yaml", shell=True)
exit(0) # file2 will be opened in a new window
file2:
import sys
yaml_file = sys.argv[1]
print("Running file2.py : yaml target: " + yaml_file)
output:
Running file1.py
Running file2.py : yaml target: target.yaml
While the other answer is a very good solution, if you are writing both files yourself you should consider importing one into the other and calling the function from the other file directly.
file1.py:
import otherfile
argument = "Hello world!"
otherfile.fancy_function(argument)
otherfile.py:
def fancy_function(arg):
print(arg)
if __name__ == "__main__":
# If the file is called directly like `python otherfile.py` this will be executed
fancy_function("I have my own world too!")
execdoesn't work like that, andexecis probably not what you should be using. You should probably be usingimportand defining and calling functions.