Executing a python file from another

Question:

I’m trying to make a compilation of all my python projects so I can document my progress as I continue to learn. In my quest to learn more, I tried learning some basic I/O. I’ve structured my library to have an index program, start_here.py at the top of my directory, a subdirectory named "projects", and 2 files dice_app.py and text_to_math.py in that subdirectory.

I’m trying to structure this so the user manually activates start_here.py, then it opens a readme file with instructions on how to use my library. I can successfully read the readme and project list txt files. The struggle I’m having right now is executing either the dice app or text to math from start_here.

This is my current system (does not work):

f = open("readme_files/index.txt")
p = open("readme_files/projects.txt")

print(f.read())

func = 0
while True:
    func = int(input("Requested Operation: "))

    if func == 0:
        print(p.read())
    elif func == 1:
        exec("projects/dice_app.py")
        break
    elif func == 2:
        exec("projects/text_to_math.py")
        break
    else:
        print("Invalid operation. Please try again.")

I’ve quintuple-checked that I have the correct relative paths and there are no misspellings for any file names. I’ve tried import statements but when I did that it automatically executed text_to_math, the second file in the projects subdirectory.

I’m not trying to execute a specific function from the file, but run the entire thing start to finish. What can I do to get this to work?

P.S. I am very new to python so I don’t know the "right way" to organize files but this is how my directory is set up.
my file structure

Asked By: Coder man

||

Answers:

Say you have the following project structure:

project_name/
    __init__.py
    main.py
    utils.py

In main.py, you could then say:

from utils.py import myfunc

You however cannot import from main to utils and from utils to main at the same time. This would cause an ImportError.

To match your filestructure:

root_dir/
    text_to_math/
        __init__.py
        dice_app.py
        text_to_math.py
    __init__.py
    start_here.py

Then in start_here.py:

from text_to_math.dice_app import myfunc
Answered By: nigel239

Use

elif func == 1:
    import projects.dice_app

Or

import subprocess

...

elif func == 1:
    subprocess.run('projects/dice_app.py')

If you put the import statement in the elif then you won’t have problems with modules getting automatically executed. Or subprocess.run is how you run terminal commands, exec is used for something else.

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.