示例#1
0
def StartFile(filename, args=[], Wait=True):
    print('**** Startfile *****')
    command = []
    command.append(filename)
    command.extend(args)
    Logger(Trace=MyTrace(GFI(CF())),
           Message='StartFile arguments: ' + str(command))
    ce = None

    try:
        if Wait:
            ce = subprocess.call(command)
            print(MyTrace(GFI(CF())),
                  str(command) + ' ' + str(Wait) + '  ' + str(ce) + ' call')
        else:
            ce = subprocess.Popen(command)
            print(MyTrace(GFI(CF())),
                  str(command) + ' ' + str(Wait) + '  ' + str(ce) + ' Popen')

        #print (MyTrace(GFI(CF())), str(command) + ' ' + str(Wait) + '  ' + str(ce))
    except OSError:

        tkinter.messagebox.showerror(
            MyTrace(GFI(CF())) + ' StartFile did a Badddddd thing ',
            'Arguments: ' + str(command) + '\nReturn code: ' + str(ce))
        return
示例#2
0
def ParseCommandLine():
    #print(DM.MyTrace(GFI(CF()), Display='line,func,file'))
    if len(sys.argv) == 1:
        return

    del sys.argv[0]  # Don't want the script name

    x = ''
    y = []
    y = [x.upper() for x in sys.argv]

    if '-H' in y or '-HELP' in y:
        DM.Logger(DM.MyTrace(GFI(CF())), 'Help was found')
        Help()

    if '-A' in y or '-ABOUT' in y:
        DM.Logger(DM.MyTrace(GFI(CF())), 'About was found')
        About()

    if '-D' in y or '-DEBUG' in y:
        DM.Logger(DM.MyTrace(GFI(CF())), 'Debug was found')
        import pdb
        pdb.set_trace()

    if '-P' in y or '-PROJECT' in y:
        DM.Logger(DM.MyTrace(GFI(CF())), 'Project was found')
        ProjectLoad()
示例#3
0
 def EditorGetTextFromTheEditTopLeve(junk):
     global EditorResults
     textPad.tag_delete('here')
     textPad.tag_add('here', 'current linestart', 'current lineend')
     textPad.tag_config('here', background="yellow", foreground="blue")
     print(MyTrace(GFI(CF())), EditorResults)
     EditorResults = textPad.get('current linestart', 'current lineend')
     print(MyTrace(GFI(CF())), EditorResults)
示例#4
0
def PerformSubstitutions():
    DM.Logger(DM.MyTrace(GFI(CF())), 'PerformSubstitutions')
    Entry1.delete(0, END)
    Entry1.insert(0, "PerformSubstitutions")
    Error = False

    # First verify project defined variables exist
    if not os.path.exists(Vars.PreferedBrowserVar.get()):
        Error = True
        tkinter.messagebox.showerror('Prefered Browser error',
                                     DM.MyTrace(GFI(CF())) +
                                     '\nPrefered Browser does not exist:\n'
                                     + Vars.PreferedBrowserVar.get())

    if not os.path.exists(Vars.PreferedEditorVar.get()):
        Error = True
        tkinter.messagebox.showerror('Prefered Editor error',
                                     DM.MyTrace(GFI(CF())) +
                                     '\nPrefered Editor does not exist:\n'
                                     + Vars.PreferedEditorVar.get())

    # These are the name that will appear in the key list
    go = False

    for w in range(len(Vars.CommandsVar)):
        x = Vars.CommandsVar[w]
        y = x  # Just for debug
        go = False  # debug stuff
        if x.lower().find("%preferedbrowser%") > -1:
            x = re.sub(r"(?i)%preferedbrowser%",
                       Vars.PreferedBrowserVar.get(), x)
            go = True
        if x.lower().find("%preferededitor%") > -1:
            x = re.sub(r"(?i)%preferededitor%",
                       Vars.PreferedEditorVar.get(), x)
            go = True
        if x.lower().find("%explorer%") > -1:
            x = re.sub(r"(?i)%explorer%", Vars.ExplorerVar.get(), x)
            go = True
        if x.lower().find("%comspec%") > -1:
            x = re.sub(r"(?i)%comspec%", os.environ["ComSpec"], x)
            go = True
        if x.lower().find("%windir%") > -1:
            x = re.sub(r"(?i)%windir%", os.environ["windir"], x)
            go = True
        if x.lower().find("%userprofile%") > -1:
            x = re.sub(r"(?i)%userprofile%", os.environ["userprofile"], x)
            go = True
        if x.lower().find("%home%") > -1:  # This is an alias for %userprofile%
            x = re.sub(r"(?i)%home%", os.environ["userprofile"], x)
            go = True

        Vars.CommandsVar[w] = x
        '''
示例#5
0
def ParseCommandLine():
    parser = \
        argparse.ArgumentParser(description='A tool to compare to directories and move files'
                                )
    parser.add_argument('-debug', help='Enable debugging', action='store_true')
    args = parser.parse_args()

    if args.debug:
        import pdb
        pdb.set_trace()
        Logger(Trace=MyTrace(GFI(CF())), Message='debug is on')
    else:
        Logger(Trace=MyTrace(GFI(CF())), Message='debug is off')
示例#6
0
def GetClipBoard():

    # DM.Logger(DM.MyTrace(GFI(CF())), 'GetClipBoard')

    try:
        temp = tk.Main.clipboard_get()
        temp = temp.replace('"', '').strip()
        if os.path.isfile(temp):
            DM.Logger(DM.MyTrace(GFI(CF())), 'From clipboard: ' + temp)
        else:
            DM.Logger(DM.MyTrace(GFI(CF())),
                      'Invalid path from clipboard: ' + temp)
    except IOError as e:
        DM.Logger(DM.MyTrace(GFI(CF())), 'No clipboard data', str(e))
示例#7
0
def DiskSpace():
    DiskSpace = shutil.disk_usage('/')
    tkinter.messagebox.showinfo(
        'Disk space', 'Free: %f Gbytes' % (DiskSpace.free / 1e9) + '\n' +
        'Used: %f Gbytes' % (DiskSpace.used / 1e9) + '\n' +
        'Total: %f Gbytes' % (DiskSpace.total / 1e9))
    Logger(Trace=MyTrace(GFI(CF())), Message='DiskSpace')
示例#8
0
def CalulateBestPoistionForNewWindow(Width=None, Height=None):
    print(DM.MyTrace(GFI(CF())),Main.geometry() + "  Width:" + str(Width), " Height:" + str(Height))
    xx = Main.geometry().split("+")
    yy = xx[0].split("x")
    main_loc = []
    main_loc.extend(yy)
    main_loc.append(xx[1])
    main_loc.append(xx[2])
    return(main_loc)
示例#9
0
def StartUpStuff():
    # -- Lots of startup stuff ------------------------------------
    # The following are defaults which will be over written by a project file

    # Get the file path and name for the log file and list file
    Vars.LogFileNameVar.set(os.path.join(os.getcwd(), 'PyRunTk.log'))
    Vars.ListFileNameVar.set(os.path.join(os.getcwd(), 'PyRunTk.txt'))
    # If the log file exits and is not removable the script is already running
    # so abort this startup
    try:
        if os.path.exists(Vars.LogFileNameVar.get()):
            os.remove(Vars.LogFileNameVar.get())
    except IOError:
        print(Vars.LogFileNameVar.get() + " is open. Script is already running")

        exit()
    DM.SetUpLogger(Vars.LogFileNameVar.get())

    Vars.AuxDirectoryVar.set(os.getcwd() + os.path.sep + 'auxfiles')

    Vars.PreferedEditorVar.set(DM.GetBestEditor())  # Not really needed

    if sys.platform.startswith('linux'):
        Vars.ProjectFileExtensionVar.set('prjl')
        Vars.ExplorerVar.set("NA")
        # Vars.ProgramFilesVar.set("NA")
        # Vars.ProgramFilesx86Var.set("NA")
    elif sys.platform.startswith('win32'):
        Vars.ProjectFileExtensionVar.set('prjw')
        Vars.ExplorerVar.set(os.environ["Windir"] + "//explorer.exe")

    Vars.AuxDirectoryVar.set(os.path.join(os.getcwd(), 'auxfiles', '.'))
    Vars.HelpFileVar.set(os.path.join(Vars.AuxDirectoryVar.get(),
                                      'PyRunTk.hlp'))

    DM.Logger(DM.MyTrace(GFI(CF())), 'OS type:' + str(os.environ.get('OS')))
    DM.Logger(DM.MyTrace(GFI(CF())), 'Uname: ' + str(platform.uname()))
    DM.Logger(DM.MyTrace(GFI(CF())),
              'Number of argument(s): ' + str(len(sys.argv)))
    DM.Logger(DM.MyTrace(GFI(CF())), 'Argument List: ' + str(sys.argv))

    Vars.DateFormatVar.set('%B  %Y/%m/%d    %A %X')

    ProjectLoad('default')
示例#10
0
 def sha1file(filename):
     sha1 = hashlib.sha1()
     f = open(filename, 'rb')
     try:
         sha1.update(f.read())
     except IOError as e:
         Logger(Trace=MyTrace(GFI(CF())), Message='whoops ' + str(e))
     finally:
         f.close()
     return sha1.hexdigest()
示例#11
0
def Help():
    print(DM.MyTrace(GFI(CF())), CalulateBestPoistionForNewWindow())
    DM.Editor(
        FileToEdit=Vars.HelpFileVar.get(),
        Title='Help',
        Height=370,
        Width=500,
        XPos=900,
        YPos=20,
    )
示例#12
0
def RemoveAFile(File, Trash):
    Logger(Trace=MyTrace(GFI(CF())),
           Message='Remove a file: ' + File + str(Trash))
    if not os.path.exists(File):
        return
    if Trash:
        try:
            send2trash(File)
            Logger(Trace=MyTrace(GFI(CF())),
                   Message='Success send2Trash: ' + File)
        except OSError:
            tkinter.messagebox.showerror('Send file to trash error. ',
                                         File + '\nPermissions?')
            Logger(Trace=MyTrace(GFI(CF())),
                   Message='Failed send2Trash: ' + File)
    else:
        try:
            os.remove(File)
            Logger(Trace=MyTrace(GFI(CF())), Message='Success remove: ' + File)
        except OSError:
            tkinter.messagebox.showerror('Delete a file error. ',
                                         File + '\nPermissions?')
            Logger(Trace=MyTrace(GFI(CF())), Message='Failed remove: ' + File)
示例#13
0
    def _build_calendar(self):
        year, month, day = self._date.year, self._date.month, self._date.day

        print(DM.MyTrace(GFI(CF()),
                         Display='line,func,file'), " year:" + str(year),
              " month:" + str(month) + " Day:" + str(day))

        # update header text (Month, YEAR)
        header = self._cal.formatmonthname(year, month, 0)
        self._header['text'] = header.title()

        # update calendar shown dates
        cal = self._cal.monthdayscalendar(year, month)
        for indx, item in enumerate(self._items):
            week = cal[indx] if indx < len(cal) else []
            print(indx, item, week)
            fmt_week = [('%02d' % day) if day else '' for day in week]
            self._calendar.item(item, values=fmt_week)
示例#14
0
def ShowKeys():
    # Prevents multiple copies from starting
    if DM.EditorToplevelName.startswith('Show keys'):
        return
    ff = 'Items: ' + str(len(Vars.KeysVar))
    x = sorted(Vars.KeysVar, key=str.lower)
    for line in x:
        ff = ff + os.linesep + line
    print(DM.MyTrace(GFI(CF())), CalulateBestPoistionForNewWindow())
    DM.Editor(
        FileToEdit=None,
        TextData=ff,
        Title='Show keys',
        Height=505,
        Width=200,
        XPos=900,
        YPos=20,
    )
示例#15
0
def About():
    AboutData = 'Aplication path: ' + os.path.dirname(os.path.abspath(__file__)) \
        + '\nApplication geometry: ' + Main.geometry() \
        + '\nScreen size:      ' + str(Main.winfo_screenwidth()) + 'x' + str(Main.winfo_screenheight()) \
        + '\nPython version:   ' + platform.python_version() \
        + '\nPlatform version: ' + platform.platform() \
        + '\nPyRunTk version:  ' + Vars.ProgramVersionNumber.get() \
        + '\nMachine:          ' + platform.machine() \
        + '\nArchitecture:     ' + str(platform.architecture())
    print(DM.MyTrace(GFI(CF())), CalulateBestPoistionForNewWindow())
    DM.Editor(
        FileToEdit=None,
        TextData=AboutData,
        Title='About',
        Height=180,
        Width=450,
        XPos=900,
        YPos=20,
    )
示例#16
0
def ShowEditFile(
    SystemEditor,
    FileToShowEdit=None,
    InitialDir=None,
    ParentTopLevel=None,
):
    if FileToShowEdit is None:
        FileToShowEdit = \
            tkinter.filedialog.askopenfilename(defaultextension='.*',
                                               initialdir=InitialDir, filetypes=[('All files', '*.*'
                                                                                  )], title='Show/Edit a file', parent=ParentTopLevel)

    Logger(Trace=MyTrace(GFI(CF())),
           Message='Show/Edit file: ' + FileToShowEdit)
    FileToShowEdit = os.path.normpath(FileToShowEdit)

    try:
        StartFile(SystemEditor, FileToShowEdit)
    except IOError:
        tkinter.messagebox.showerror(
            'Show/Edit file error',
            'Show/Edit file error:\n' + SystemEditor + '\n' + FileToShowEdit)
        return
示例#17
0
 def EditorGetTextFromTheEditTopLevel(junk):
     global EditorResults
     print(MyTrace(GFI(CF())), EditorResults)
     EditorResults = textPad.get('current linestart', 'current lineend')
     print(MyTrace(GFI(CF())), EditorResults)
示例#18
0
 def ButtonHandle(data):
     global ButtonResult
     ButtonResult = data
     print(MyTrace(GFI(CF())), ButtonResult, data)
     MyMBMain.destroy()
     return data
示例#19
0
def MyMessageBox(
    Title='MyMessageBox',
    LabelText=[],
    TextMessage=None,
    bgColor='black',
    fgColor='white',
    Buttons=['Close'],
    Center=None,
    Geometry=None,
):
    def ButtonHandle(data):
        global ButtonResult
        ButtonResult = data
        print(MyTrace(GFI(CF())), ButtonResult, data)
        MyMBMain.destroy()
        return data

    MyMBMain = Tk()  # Create a main window
    MyMBMain.title(Title)
    MyMBMain.config(bg=bgColor)

    # This prints out the window geometry on configure event

    MyMBMain.bind('<Configure>',
                  lambda e: ShowResize('MyMessageBox', MyMBMain))

    # parses the geometry parameter

    print(MyTrace(GFI(CF())), Center, Geometry)
    if not Geometry:
        Geometry = '250x250+10+20'
    Geom = Geometry.split('+')
    Size = Geom[0].split('x')
    XPos = int(Geom[1])
    YPos = int(Geom[2])
    XSize = int(Size[0])
    YSize = int(Size[1])

    # print(MyTrace(GFI(CF())), XPos, YPos, XSize, YSize)

    if 'None' in str(type(Center)):  # Uses the Geometry option
        print(MyTrace(GFI(CF())), 'Geometry: ', Geometry)
    elif 'tkinter.Tk' in str(type(Center)):

        # center of the item pointed to
        # parses the geometry of the CenterParam window

        CenterParamGeometry = Center.geometry()

        # These are the values from the passed in parameters

        CenterParamGeom = CenterParamGeometry.split('+')
        CenterParamSize = CenterParamGeom[0].split('x')
        CenterParamXPos = int(CenterParamGeom[1])
        CenterParamYPos = int(CenterParamGeom[2])
        CenterParamXSize = int(CenterParamSize[0])
        CenterParamYSize = int(CenterParamSize[1])

        # These are the values from the message box

        MyMBMainGeom = Geometry.split('+')
        MyMBSize = MyMBMainGeom[0].split('x')
        MyMBXPos = int(MyMBMainGeom[1])
        MyMBYPos = int(MyMBMainGeom[2])
        MyMBXSize = int(MyMBSize[0])
        MyMBYSize = int(MyMBSize[1])

        # This is the calculated position for the messagebox

        XPos = CenterParamXPos + CenterParamXSize / 2 - MyMBXSize / 2
        YPos = CenterParamYPos + CenterParamYSize / 2 - MyMBYSize / 2
    elif 'center' in Center.lower():

        # center of the screen

        XPos = MyMBMain.winfo_screenwidth() / 2 - XSize / 2
        YPos = MyMBMain.winfo_screenheight() / 2 - YSize / 2
        print(MyTrace(GFI(CF()), Display='line'), Center.upper())

    MyMBMain.geometry('%dx%d+%d+%d' % (XSize, YSize, XPos, YPos))

    # Add some buttons
    # Theoretically an unlimited number of buttons can be added

    ButtonFrame = Frame(MyMBMain, relief=SUNKEN, bd=1, bg=bgColor)
    ButtonFrame.pack(side=TOP, expand=FALSE, fill=X)
    for a in reversed(Buttons):
        Button(ButtonFrame, text=a,
               command=lambda a=a: ButtonHandle(a)).pack(side=RIGHT)

    # This adds labels for each message
    # Theoretically an unlimited number of labels can be added

    for x in range(len(LabelText)):

        Label(MyMBMain,
              text=LabelText[x],
              relief=GROOVE,
              fg=fgColor,
              bg=bgColor).pack(expand=FALSE, fill=k.X)

    # A text box http://effbot.org/tkinterbook/text.htm

    if TextMessage:
        Yscrollbar = tk.Scrollbar(MyMBMain, orient=tk.VERTICAL)
        Yscrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        Xscrollbar = tk.Scrollbar(MyMBMain, orient=tk.HORIZONTAL)
        Xscrollbar.pack(side=tk.BOTTOM, fill=tk.X)

        Textbox = tk.Text(
            MyMBMain,
            wrap=tk.NONE,
            width=XSize,
            height=YSize,
            bg=bgColor,
            fg=fgColor,
            yscrollcommand=Yscrollbar.set,
            xscrollcommand=Xscrollbar.set,
        )
        Textbox.pack()

        Yscrollbar.config(command=Textbox.yview)
        Xscrollbar.config(command=Textbox.xview)
        Textbox.insert(tk.END, TextMessage)

    MyMBMain.resizable(1, 1)
    MyMBMain.mainloop()
示例#20
0
def Editor(
    FileToEdit=None,
    TextData=None,
    Title='Editor',
    AutoReload=False,
    Width=100,
    Height=400,
    XPos=900,
    YPos=100,
):
    print("AutoReload: " + str(AutoReload))
    if FileToEdit:
        fp = open(FileToEdit, 'r')
        text = fp.read()
        fp.close()
        print(FileToEdit + " Size: " + str(os.path.getsize(FileToEdit)))
    if TextData:
        text = TextData
    global EditorToplevelName

    EditorToplevel = Tk()
    EditorToplevel.title(" " + Title)
    EditorToplevel.Geometry = '10x10+200+0'
    EditorToplevel.geometry('%dx%d+%d+%d' % (Width, Height, XPos, YPos))
    EditorToplevelName = Title
    print(MyTrace(GFI(CF())), '>>' + EditorToplevelName + '<<')

    def destroyEditor():
        global EditorToplevelName
        EditorToplevel.destroy()
        EditorToplevelName = 'None'
        return

    EditorToplevel.protocol('WM_DELETE_WINDOW', destroyEditor)

    textPad = Text(EditorToplevel, relief=SUNKEN, wrap=WORD)
    sbar = Scrollbar(EditorToplevel)
    sbar['command'] = textPad.yview
    textPad['yscrollcommand'] = sbar.set
    sbar.pack(side=RIGHT, fill=Y)

    # This prints out the window geometry on configure event
    # EditorToplevel.bind("<Configure>",lambda e:ShowResize("Edit window: ", EditorToplevel))

    # This handles getting the text from the edit top level

    def EditorGetTextFromTheEditTopLevel(junk):
        global EditorResults
        print(MyTrace(GFI(CF())), EditorResults)
        EditorResults = textPad.get('current linestart', 'current lineend')
        print(MyTrace(GFI(CF())), EditorResults)

    textPad.bind('<Button-1>', EditorGetTextFromTheEditTopLevel)

    # create a menu

    # def exit_command():
    # destroyEditor()

    # def save_command():
    #file = tkinter.filedialog.asksaveasfile(mode='w')
    # if file != None:

    # slice off the last character from get, as an extra return is added

    #data = self.textPad.get('1.0', END + '-1c')
    # file.write(data)
    # file.close()

    #menu = Menu(EditorToplevel)
    # EditorToplevel.config(menu=menu)
    #filemenu = Menu(menu)
    #menu.add_cascade(label='File', menu=filemenu)
    #filemenu.add_command(label='Save', command=save_command)
    # filemenu.add_separator()
    #filemenu.add_command(label='Exit', command=exit_command)

    # end of menu creation

    textPad.delete('1.0', END)
    textPad.insert('1.0', text)
    textPad.mark_set(INSERT, '1.0')
    textPad.focus()
    textPad.pack(expand=YES, fill=BOTH)
    EditorToplevel.mainloop()
示例#21
0
def ReturnCallback(event):
    command = Entry3.get().lower()

    DM.Logger(DM.MyTrace(GFI(CF())), "command: " + command)
    print(DM.MyTrace(GFI(CF())), "command: " + command)

    # The following are built in commands
    if command == '=about':
        Entry2.delete(0, END)
        Entry3.delete(0, END)
        About()
        return
    elif command == '=exit':
        ShutDown()
        return
    elif command == '=help':
        Entry2.delete(0, END)
        Entry3.delete(0, END)
        Help()
        return
    elif command == '=cal':
        Entry2.delete(0, END)
        Entry3.delete(0, END)
        ShowCalender()
        return
    elif command == '=keyedit':
        DM.StartFile(Vars.PreferedEditorVar.get(), [
                     Vars.ProjectFileNameVar.get()])
        return
    elif command == '=load':
        Entry2.delete(0, END)
        Entry3.delete(0, END)
        ProjectLoad()
        return
    elif command == '=reload':
        Entry2.delete(0, END)
        Entry3.delete(0, END)
        ProjectLoad('default')
        ShowKeys()
        return
    elif command == '=keyshow':
        Entry2.delete(0, END)
        Entry3.delete(0, END)
        ShowKeys()
        return
    elif command == '=logshow':
        Entry2.delete(0, END)
        Entry3.delete(0, END)
        print(DM.MyTrace(GFI(CF())), CalulateBestPoistionForNewWindow())
        DM.Editor(
            FileToEdit=Vars.LogFileNameVar.get(),
            Title='Log',
            Height=750,
            Width=750,
            XPos=500,
            YPos=10,
        )
        return

    # The following are for user added commands

    for line in Vars.CommandsVar:
        if line.lower().find(command.lower() + '~=') == 0:
            MyList = line.split('~=')  # separate the key from the command
            pp = pprint.PrettyPrinter()
            pp.pprint(MyList)

            # del MyList[0]  # don't want the first item

            # separate the command and parameter
            CmdList = MyList[1].split('??')
            Arg1 = str(CmdList[0].strip())
            Arg2 = str(CmdList[1].strip())
            if not os.path.exists(Arg1):
                tkinter.messagebox.showerror('Error: ' + DM.MyTrace(GFI(CF())),
                                             'Command does not exist:\n' + Arg1)
                return

            print(DM.MyTrace(GFI(CF())), Arg1 + "  " + Arg2)
            CList = [Arg2]  # Convert command parameters to list

            print(DM.MyTrace(GFI(CF())), CList)

            Entry1.delete(0, END)
            Entry1.insert(0, "Working")

            # pdb.set_trace() #todo

            DM.StartFile(Arg1, CList)
            DM.EditorResults = ""
            Entry2.delete(0, END)
            Entry3.delete(0, END)
示例#22
0
def ProjectLoad(LoadType='none'):
    Entry1.delete(0, END)
    Entry1.insert(0, "Working")
    DM.Logger(DM.MyTrace(GFI(CF())), 'Aux Directory: '
              + Vars.AuxDirectoryVar.get())
    DM.Logger(DM.MyTrace(GFI(CF())), 'Project File Extension: '
              + Vars.ProjectFileExtensionVar.get())
    DM.Logger(DM.MyTrace(GFI(CF())), 'LoadType: ' + LoadType)

    if LoadType == 'default':  # Use the default project file
        Vars.ProjectFileNameVar.set(os.path.join(Vars.AuxDirectoryVar.get(),
                                                 'PyRunTk.'
                                                 + Vars.ProjectFileExtensionVar.get()))
    else:  # Prompt user to select a project file
        Vars.ProjectFileExtensionVar.get()
        Vars.ProjectFileNameVar.set(tkinter.filedialog.askopenfilename(
            defaultextension=Vars.ProjectFileExtensionVar.get(),
            filetypes=[('Project file', 'PyRunTk*.*'
                        + Vars.ProjectFileExtensionVar.get()),
                       ('All files', '*.*')],
            initialdir=Vars.AuxDirectoryVar.get(),
            initialfile='PyRunTk.'
            + Vars.ProjectFileExtensionVar.get(),
            title='Load a PyRunTk project file',
            parent=Main,
        ))
    Vars.ProjectFileNameVar.set(
        os.path.normpath(Vars.ProjectFileNameVar.get()))

    DM.Logger(DM.MyTrace(GFI(CF())), 'Project Load: '
              + Vars.ProjectFileNameVar.get())

    try:
        f = open(Vars.ProjectFileNameVar.get(), 'r')
    except IOError:
        tkinter.messagebox.showerror('Project file error',
                                     'Requested file does not exist.\n>>'
                                     + Vars.ProjectFileNameVar.get() + '<<')
        return

    lines = f.readlines()
    f.close()
    try:
        if not 'PyRunTk.py project file ' + sys.platform in lines[0]:
            tkinter.messagebox.showerror('Project file error',
                                         'Not a valid project file.\nproject file' + '\n'
                                         + lines[0])
            DM.Logger(DM.MyTrace(GFI(CF())), 'PyRunTk.py project file '
                      + lines[0].strip())
            return
    except:
        tkinter.messagebox.showerror('Project file error',
                                     'Unable to read project file'
                                     + Vars.ProjectFileNameVar.get())
        DM.Logger(DM.MyTrace(GFI(CF())),
                  'PyRunTk project file. Unable to read file')
        return

    # remove the first line so it won't be added to the comments list
    del lines[0]

    Vars.CommentsListVar.clear()
    Vars.KeysVar.clear()
    Vars.CommandsVar.clear()

    start = BooleanVar
    tmp = ''
    for line in lines:
        line = line.strip()

        if line.startswith('#'):  # All lines with # in the first column are comments
            Vars.CommentsListVar.append(line)
        else:
            # first we get the user defined variables from the project file
            if line.startswith('DateFormat~='):
                t = line.split('=')
                Vars.DateFormatVar.set(t[1].strip())
            elif line.startswith('PreferedEditor~='):
                t = line.split('~=')
                if sys.platform.startswith('win32'):
                    t[1] = t[1].replace('%ProgramFiles(x86)%', os.environ[
                                        "ProgramFiles(x86)"])
                    t[1] = t[1].replace(
                        '%ProgramFiles%', os.environ["ProgramFiles"])
                Vars.PreferedEditorVar.set(t[1])
            elif line.startswith('PreferedBrowser~='):
                t = line.split('~=')
                if sys.platform.startswith('win32'):
                    t[1] = t[1].replace('%ProgramFiles(x86)%', os.environ[
                                        "ProgramFiles(x86)"])
                    t[1] = t[1].replace(
                        '%ProgramFiles%', os.environ["ProgramFiles"])
                Vars.PreferedBrowserVar.set(t[1])
            elif line.count("~=") > 0:  # Now get the user command strings
                a = line.strip()
                t = a.split('~=')
                if sys.platform.startswith('win32'):
                    t[1] = t[1].replace('%ProgramFiles(x86)%', os.environ[
                                        "ProgramFiles(x86)"])
                    t[1] = t[1].replace(
                        '%ProgramFiles%', os.environ["ProgramFiles"])
                Vars.KeysVar.append(t[0])
                Vars.CommandsVar.append(t[0] + "~=" + t[1])
            elif line.count("=") == 1:  # This is a built in command
                Vars.KeysVar.append(line)

    DM.Logger(DM.MyTrace(GFI(CF())), "Keys: " + str(Vars.KeysVar))

    Vars.KeysVar.sort()
    Vars.KeysVar.sort(key=len, reverse=False)

    Vars.CommandsVar.sort()
    DM.Logger(DM.MyTrace(GFI(CF())), "Size of CommandsVar: " +
              str(len(Vars.CommandsVar)))
    DM.Logger(DM.MyTrace(GFI(CF())),
              "Size of KeysVar: " + str(len(Vars.KeysVar)))
    DM.Logger(DM.MyTrace(GFI(CF())), "Size of CommentsListVar: " +
              str(len(Vars.CommentsListVar)))

    PerformSubstitutions()
    DM.Logger(DM.MyTrace(GFI(CF())), 'Project opened: '
              + Vars.ProjectFileNameVar.get())
示例#23
0

# ------------------------------

# Try to get source file from clipboard


def GetClipBoard():

    # DM.Logger(DM.MyTrace(GFI(CF())), 'GetClipBoard')

    try:
        temp = tk.Main.clipboard_get()
        temp = temp.replace('"', '').strip()
        if os.path.isfile(temp):
            DM.Logger(DM.MyTrace(GFI(CF())), 'From clipboard: ' + temp)
        else:
            DM.Logger(DM.MyTrace(GFI(CF())),
                      'Invalid path from clipboard: ' + temp)
    except IOError as e:
        DM.Logger(DM.MyTrace(GFI(CF())), 'No clipboard data', str(e))


# ------------------------------

if __name__ == '__main__':

    print(MyTrace(GFI(CF()), Display='line,func,file'))

    MessageTimeOut(Message='Message timeout test', TimeOut=2000)