Running a python file within a different directory

Viewed 208

How could I run the entirety of test.py from main.py. Both main.py and test.py is allocated within the application folder. The test.py file is within the app folder. How would I be able to achieve this, the code I have below does not work?

Directories:

application folder
├── appFolder
│   └──test.py
└── main.py

Main.py:

from .appFolder import test
from subprocess import call
call(["Python3","test.py"])
1 Answers

You don't need to import anything, just reference the folder name in main.py. To make it more robust, you should probably use a relative file otherwise you might get some odd results depending on where main.py is called from.

import os.path
from subprocess import call

d = os.path.dirname(os.path.realpath(__file__))  # application folder
call(["python3", f"{d}/appFolder/test.py"])

See also: https://stackoverflow.com/a/9271479/1904146

Related