KiiVoZin
KiiVoZin

Reputation: 15

How can I run an entire Python3 file from another Python3 file?

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

Answers (2)

Parsa Dany
Parsa Dany

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

user14687465
user14687465

Reputation:

exec(open("main2.py").read())

Source: https://www.delftstack.com/howto/python/python-run-another-python-script/

Upvotes: 2

Related Questions