1

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 
17
  • 1
    1) Yes 2) If you want to use this code in the future and maintain it, you should really refactor it, because else you will get headaches maintaining it Commented Mar 25, 2022 at 8:10
  • Something like jupytext might help with this. Commented Mar 25, 2022 at 8:12
  • import does exactly what you want. Commented Mar 25, 2022 at 8:18
  • 1
    @tripleee You can't import a Jupyter notebook file like that. They are formatted in JSON. Commented Mar 25, 2022 at 8:21
  • The OP specifically asks about a Python file. Perhaps they should clarify what exactly they mean. Commented Mar 25, 2022 at 8:22

2 Answers 2

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

Using exec is a serious security risk, and in general running subprocesses is not encouraged and has lots of considerations (e.g. what do to, and how to monitor child process end, how to handle or even receive the errors, what happens when main process crash - you get leaky process etc.)
He asked how, and gave him answer :/ . I think you should write your own answer, and explain to him why it is a bad idea to have subprocesses. I'm not that much experienced.
1

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

10 Comments

I believe this works too, but I haven't tried it. Thanks!
Not my downvote, but running Python as a subprocess of itself is dubious advice unless you specifically require the isolation you get from running a separate process (such as separate control over signals etc).
if they want to "run" the file - just need to import it (unless there are considerations to separate the memory space)
I agree with @tripleee - invoking subprocesses has a lot of issues, and a lot of care needs to be taken when doing so
Dear @MarkSetchell, I just proposed an idea, I don't know the exact case of the main problem, reader can google solutions and pick one of them that fits his case. These answers will be used by too many people later. And also i did not down vote, thank you all.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.