我正在使用 Python 制作一种解释型语言,名为 Spearhead。我的终端在尝试运行命令“+r {+r 是我运行文件的方式} [要解释的文件路径]”时,给出了自定义错误“目录无效”。在没有终端解析它的情况下运行基本 Python 命令时,我得到了完全相同的错误:“Errno2:没有这样的文件或目录”有人能告诉我为什么会发生这种情况吗?
包含有问题代码的 GitHub repo 分支: 问题
如果你不能使用 GitHub,请编写代码:
终端.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])
解释器.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
文件结构:
矛头:
Y_前端.py
终端.py
test.spearhead [找不到的文件,如果你需要内容,请访问 GitHub]
原始执行:
init .py [空文件,由于愚蠢的自动更正,不包含 __ __]
解释器.py
raw_exec 嵌套在 Spearhead 文件夹内。
您的 Interpreter.py 文件存在一些问题。请检查以下行:
如果您只想将项目添加到列表中, 请更改
insert
为。Insert 需要 2 个参数,而您只传递一个。append
我不确定您希望此代码返回什么,但这
return requirements
将始终在 Terminal.py 中抛出您的自定义Directory invalid
异常,因为运行您的进程的响应始终为空。您可能需要删除该行。这是我通过这些改变得到的: