Reputation: 15
I have 2 .py files: test.py and test2.py
test.py:
import test2
print("This is test.py")
test2.py:
print("This is test2.py")
When I run test.py, I get:
This is test.py
How can I print "This is test2.py" by running test2.py from test.py?
Solution found:
test.py:
print("This is test.py")
exec(open("test2.py").read())
test2.py:
if __name__ == '__main__':
print("This is test2.py")
Output:
This is test.py
This is test2.py
Upvotes: 1
Views: 127
Reputation: 35
I think that there are many ways to do, but I think that subproccess will help you:
subprocess.run(["python", "path/to/test2.py"])
This will execute a shell command to open python and then tell him(python) to open and execute test2.py. Here is the documentation: https://docs.python.org/3/library/subprocess.html
Upvotes: 1
Reputation:
exec(open("main2.py").read())
Source: https://www.delftstack.com/howto/python/python-run-another-python-script/
Upvotes: 2