Search code examples
pythonterminalinterpreter

Python is not finding location of file to parse, even when i have triple-checked it is still there


I am making a interpreted language using python, named Spearhead. My terminal, when trying to run the command "+r {+r is how i run files} [path to file to be interpreted]" It gives me my custom error "Directory invalid" Upon running the base python command without the terminal to parse it, I get the exact same error: "Errno2: no such file or directory" Can someone tell me why this is happening?

Branch of GitHub repo containing problematic code: Issue

Code if you cant use GitHub:

Terminal.py:

import subprocess
import sys
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
dir_path = dir_path + "\\Y_frontend.py"
def run_c(c):
try:
    #start terminal and get output
    output = subprocess.check_output(c, shell=True, 
    stderr=subprocess.DEVNULL).decode()
    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"
        print("Enter +h into command line for terminal guide")
        u_i = input("cmd< ")
        if u_i.lower() == "exit":
            break
        #get user input and check if it is "+help"
        elif u_i[:2] == "+h":
            print("Terminal instructions:")
            print("Press the enter key or enter \"exit\" into the command line to leave the terminal")
            print("Enter the command \"+r [replace with path of .spearhead file to be ran]\" to run a .spearhead file via the Spearhead Interpreter")
        #get user input and check if it is "+r"
        elif u_i[:2] == "+r":
            try:
                r = subprocess.run(["python", dir_path, u_i], capture_output=True, text=True).stdout.strip("\n")
                print(r)
                if r == '':
                    print("Directory invalid")
            except FileNotFoundError as e:
                print("Directory invalid")
            continue
        else:
            print("Invalid 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.Interpreter import *
from sys import *
import os
if __name__ == '__main__':
    parse(argv[1])

Interpreter.py:

import re
def lexer(contents):
    lines = contents.split('\n')
    for line in lines:
    chars = list(line)
    requirements = []
    if re.match('require', line):
        r = True
    if re.search(' boolOperators', line):
         b = True
    if b and r == True:
        requirements.insert('boolOperators')
        line = ''
        return requirements
    temp_str = ""
    tokens = []
    quote_count = 0
    for char in chars:
        if char == '"' or char == "'":
            quote_count += 1
        if quote_count % 2 == 0:
            in_quotes = False
        else:
            in_quotes = True
        if char == " " and in_quotes == False:
            tokens.append(temp_str)
            temp_str = ""
        else:
            temp_str += char
    tokens.append(temp_str)
    print(tokens)
def parse(parsed_data):
    parsed_data = parsed_data.replace(parsed_data[:3], '')
    parsed_data = re.sub('\"', '', parsed_data)
    c = open(parsed_data, "r")
    cl = c.read()
    tokens = lexer(cl)
    return tokens

File structure:

Spearhead:

Y_frontend.py

Terminal.py

test.spearhead [file that it cant find, if you need contents, GitHub]

raw_exec:

init.py [empty file, doesnt contain the __ __ because stupid autocorrect]

Interpreter.py

raw_exec is nested inside of the Spearhead folder.


Solution

  • You have some problems at your Interpreter.py file. Check this line:

    requirements.insert('boolOperators')
    

    Change insert to append if you just want to add items to the list. Insert expects 2 arguments, and you are only passing one. Insert explanation

    I'm not sure what you expect this code to return, but this return requirements will always throw your custom Directory invalid exception in Terminal.py because the response from running your process will always be empty. You probably need to remove that line.

    This is what I got with these changes: Termina.py Execution