如何从路径运行 python 脚本,同时包含额外的文件,如 .txt



我目前正在开发一个脚本,该脚本允许您输入python脚本的路径并运行它,这对于运行相同类型的代码以进行故障排除非常有用,因为有时程序崩溃CMD,您必须重新输入位置ECT的所有信息。

目前它运行良好,但是它出现了错误

Traceback (most recent call last): File "E:Coding Type of stuffPythonTestingtest.py", line 1, in <module> print(open("text.txt","r").readlines()[0]) FileNotFoundError: [Errno 2] No such file or directory: 'text.txt'

我知道为什么会发生这种情况,但是有什么解决方法吗?

python脚本运行器的当前代码:

import tkinter as tk
from subprocess import Popen
try:
    path = (open("path.txt","r").readlines())[0]
    print(path)
except:
    path = "Enter path..."
    open("path.txt","w").write("")
def on_entry_click(event):
    if entry.get() == path:
       entry.delete(0, "end")
       entry.insert(0, '')
       entry.config(fg = 'black')
def on_focusout(event):
    if entry.get() == '':
        entry.insert(0, path)
        entry.config(fg = 'grey')
def get_input(box):
    try:
        path = box.get()
        if path != "Enter path...":
            open("path.txt","w").write(path)
            Popen('python "'+path+'"')
        else:
            print("No path entered")
    except:
        print("That path does not work")
root = tk.Tk()
root.geometry("375x50")
label = tk.Label(root, text="Path: ")
label.grid(row = 0, column = 0)
entry = tk.Entry(root, bd=1, width = 50)
entry.insert(0, path)
entry.bind('<FocusIn>', on_entry_click)
entry.bind('<FocusOut>', on_focusout)
entry.config(fg = 'grey')
button = tk.Button(root, text = "Run", command = lambda: get_input(entry))
entry.grid(row = 0, column = 1)
button.grid(row = 1)
root.mainloop()

您可以先使用以下方法检查文件是否存在:

import os
path_exists = os.path.isdir("###your_dir###")
file_exists = os.path.exists("text.txt")

相关内容

  • 没有找到相关文章

最新更新