pythonterminalsubprocessinterpreter

can't find '__main__' module | breaking subprocess terminal command


I am creating a programming language named Spearhead using Python, I have a parser named Parser.py, inside a subfolder of the Spearhead folder this is all contained in named raw_exec [that has a empty __init__ file], a simple program to run the parser, named Y_frontend.py, and a terminal-like program called Terminal.py (made with the subprocess module) that I am using to let the user do the command python [path of Y_frontend] [path of .spearhead program to be ran through Parser.py] by writing +r [name of file to be ran] in Terminal.py, so you can run a program via Terminal.py. Every time I try it, it throws an error

Terminal.py:

import subprocess
from Y_frontend import *
import sys
import os
def run_c(c):
    try:
        #start terminal and get output
        output = subprocess.check_output(c, shell=True, stderr=subprocess.STDOUT)
        return output.decode()
    except subprocess.CalledProcessError as e:
        #incase i need to handle errors later
        return e.output.decode()
def main():
    while True:
        #get user input and check if it is "exit"
        u_i = input("cmd< ")
        if u_i.lower() == "exit":
            break
        #get user input and check if it is "+r"
        elif u_i[:2] == "+r":
            try:
                subprocess.run(["python", dir_path, u_i])
            except FileNotFoundError:
                print("Directory invalid")
            continue
        else:
            print("Invalid command, or shell command")
        #actually run the commands provided and print output
        output = run_c(u_i)
        print(output)
#__name == __main__ so it actually works, although i honestly dont understand this at all, it makes everything work like a charm
if __name__ == '__main__':
    main()

Y_frontend.py:

from raw_exec.Parser import *
from sys import *
import os
import Terminal
dir_path = os.path.dirname(os.path.realpath(__file__))
if __name__ == '__main__':
    parse(argv[1])

Parser.py [inside of subfolder raw_exec that contains an empty init file]:

import Terminal
import Y_frontend
def parse(parsed_data):
    parsed_data = parsed_data.replace(parsed_data[:3], '')
    c = open(parsed_data, "r")
    cl = c.readlines()
    for ln in cl:
        print(ln)
    return c

File structure:

Spearhead

|

+-- Terminal.py

|

+-- Y_frontend.py

|

+--raw_exec INCLUDES FILES: Parser.py

ISSUE:

I created a simple file named test.spearhead, with the contents:

LINE 1
LINE 2
LINE 3
LINE 4
LINE 5

Upon executing in the command line of Terminal.py

+r "C:\Users\username\Desktop\Spearhead\test.spearhead"

I get the error:

C:\Users\username\AppData\Local\Programs\Python\Python312\python.exe: can't find '__main__' module in 'C:\\Users\\username\\Desktop\\Spearhead'

Solution

  • dir_path was formatted wrong, and it couldnt find the correct directory/path.