我正在使用 Python 创建一种名为 Spearhead 的编程语言,我有一个名为
Parser.py
的解析器,位于 Spearhead
文件夹的子文件夹中,这全部包含在名为 raw_exec [有一个空 __init__
文件] 中,这是一个简单的运行解析器的程序,名为 Y_frontend.py
,以及一个名为 Terminal.py
的类似于终端的程序(由 subprocess
模块制作),我用它来让用户通过在中写入 python [path of Y_frontend] [path of .spearhead program to be ran through Parser.py]
来执行命令 +r [name of file to be ran]
Terminal.py,这样你就可以通过Terminal.py运行程序。每次我尝试时都会抛出错误
终端.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 [包含空 init 文件的子文件夹 raw_exec 内部]:
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
文件结构:
矛头
|
+-- 终端.py
|
+-- Y_frontend.py
|
+--raw_exec 包含文件:Parser.py
问题:
我创建了一个名为
test.spearhead
的简单文件,其内容为:
LINE 1
LINE 2
LINE 3
LINE 4
LINE 5
在 Terminal.py 的命令行中执行时
+r "C:\Users\username\Desktop\Spearhead\test.spearhead"
我收到错误:
C:\Users\username\AppData\Local\Programs\Python\Python312\python.exe: can't find '__main__' module in 'C:\\Users\\username\\Desktop\\Spearhead'
dir_path 格式错误,无法找到正确的文件。