I maked a script who need to pars 3D printer log files and export it to .xlsx.
I finished that but now I need to make GUI for that script, I finished almost everything except the one thing. I have function like this
def run(templatefilename):
#LIST OF PRINTER LOG FILES
listOfLogFiles = glob.glob(r"newPrintLogs\*.txt")
for logfile in listOfLogFiles:
#PARSING PRINTER LOG FILE
data = parsPrintingLog(logfile)
#WRITE EXCEL FILE
excelWrite(data, templatefilename)
# MOVE FINISHED FILES
dst = "finishedPrintLogs\\" + logfile.split('\\')[-1]
src = r"" + str(logfile)
shutil.move(src, dst)
consoleLog(src + " " + "successfully finished and moved to" + " " + dst)
# print (src, "successfully finished and moved to", dst)
and from this function I need to export the "# MOVE FINISHED FILES".
Before I've maked GUI I used print for printing where the log is moved, but now I don't know how to print it in GUI textbox, it's not necessary to be a textbox, I only need to show that in my GUI application.
Maybe i misunderstand your question, but from what I gathered you are wanting to dump the contents of your log file to be display in the tkinter GUI.
You could use a ttk ScrolledText widget.
Small minimal example"
textbox = ttk.ScrolledText(parent)
log_contents = open(log_file, "r").read()
textbox.insert("end", log_contents)
If you have some other encoding for your log file you could this for example
in textbox.insert log_contents could be decoded to utf-8 by log_contents.decode("utf-8")
You can then handle scrolling, searching the scrolledtext widget highlight found words etc by additional methods to search your log files contents for example.
Related
I am trying to create a program that allows the user to open a pre-existing file and save current files. For opening a file I am using:
dlg = QFileDialog(self, "Open", "", "Yaml(*.yaml)")
filenames = QStringList()
if dlg.exec_():
filenames = dlg.selectedFiles()
FILE_NAME = str(QFileInfo(filenames[0]).baseName())
For saving files I am using:
_fileName = QFileDialog().getSaveFileName(self, "Save", "./", "Yaml(*.yaml)")
FILE_NAME = str(QFileInfo(_fileName).baseName())
However, graphically I am noticing differences between the open and save methods.
I know I am not using QFileDialog.getOpenFileName(...)
This is because QFileDialog.getSaveFileName(...) outputs a bunch of errors when loading the GUI.
Failed enumerating UDisks2 objects: "org.freedesktop.DBus.Error.Disconnected"
"Not connected to D-Bus server"
Is there anyway that I can use QFileDialog to save files? Note that
QFileDialog() by default has an "Open" button, is there anyway to change this to "Save"
I found a solution.
QFileDialog has a method called setAcceptMode(QFileDialog.AcceptMode) which allows you to change between Open and Save. http://pyqt.sourceforge.net/Docs/PyQt4/qfiledialog.html#setAcceptMode
Usage for open:
QFileDialog.setAcceptMode(QtGui.QFileDialog.AcceptOpen)
Usage for Save:
QFileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
I can not find a way using the the Tkinter tkFileDialog.askopenfilename / Open() method to get a file name of an already opened file. At least on Windows 7 anyway.
Simply need to return the filename selected, but when I select an 'opened' file I get the "This file is in use" popup. Any searches for getting filenames seems to always point back to using FileDialog.
There seems to be the same question but using c# here:
Open File Which is already open in window explorer
Are there any ways not listed that can be used to arrive at this? A file selection popup that doesn't fail on already opened files on Windows 7?
Python 2.7.11
Windows 7_64
Selection dialog:
opts = {}
opts['title'] = 'Select file.'
filename = tkFileDialog.Open(**opts).show()
or
filename = tkFileDialog.askopenfilename(**opts)
Which are the same as askopenfilename calls Open().show() which in turn is calling command = "tk_getOpenFile".
Searching tk_getOpenFile shows nothing to override this behavior.
Any pointers here would be much appreciated.
Update:
So as to not reiterate everything that's been gone over here's the break down of the Tkinter 8.5 FileDialog.
def askopenfile(mode = "r", **options):
"Ask for a filename to open, and returned the opened file"
filename = Open(**options).show()
if filename:
return open(filename, mode)
return None
def askopenfilename(**options):
"Ask for a filename to open"
return Open(**options).show()
Both call the Open class but askopenfile follows up with an open(file), here:
class Open(_Dialog):
"Ask for a filename to open"
command = "tk_getOpenFile"
def _fixresult(self, widget, result):
if isinstance(result, tuple):
# multiple results:
result = tuple([getattr(r, "string", r) for r in result])
if result:
import os
path, file = os.path.split(result[0])
self.options["initialdir"] = path
# don't set initialfile or filename, as we have multiple of these
return result
if not widget.tk.wantobjects() and "multiple" in self.options:
# Need to split result explicitly
return self._fixresult(widget, widget.tk.splitlist(result))
return _Dialog._fixresult(self, widget, result)
UPDATE2(answerish):
Seems the windows trc/tk tk_getOpenFile ultimately calls
OPENFILENAME ofn;
which apparently can not, at times, return a filename if the file is in use.
Yet to find the reason why but regardless.
In my case, needing to reference a running QuickBooks file, it will not work using askopenfilename().
Again the link above references someone having the same issue but using c# .
I have a script that reads information from two different files, and writes output to a third file. I have an error catch (the goal of the error catch is to display any IDs that did not get processed by the script) at the very end that uses a ctypes windows message box. Currently, the script does not actually finish writing to the output file until I click "OK" on the error message box. I would like the program to, instead, finish writing to the output file regardless of me pressing "OK". Is this possible to do?
The script:
'''select newest reference file'''
directory = 'C:\User\Python test\Folder1'
newest = max(glob.iglob(os.path.join(directory, '*.txt')), key=os.path.getctime)
timestamp = time.strftime("%Y_%m_%d - %H_%M_%S")
'''Get IDS to be read'''
idlist = open('C:\User\Python test\ID List.txt').read().splitlines()
'''Print or write lines associated with selected IDS'''
output = open('C:\User\Python test\%s.txt' % timestamp, 'w')
with open(newest, 'r') as f:
head = f.readline().strip()
output.writelines(head + "\n")
for referenceline in f.read().strip().split("\n"):
for ids in idlist:
if ids in referenceline:
output.writelines(referenceline.replace(" ", "") + "\n")
idlist.remove(ids)
text = '\n'.join(idlist)
ctypes.windll.user32.MessageBoxW(0, u"%s" %text, u"IDs not found:", 0)
This one was pretty simple. I just needed to close the file before the error catch.
Code:
output.close()
text = '\n'.join(idlist)
ctypes.windll.user32.MessageBoxW(0, u"%s" %text, u"IDs not found:", 0)
I am writing a program in python on Ubuntu. In that program I am struggling to select a file using the command askopenfilename on a remote network connected RaspberryPi.
Can anybody guide me on how to select a file from the remote machine using askopenfilename command or something similar?
from Tkinter import *
from tkFileDialog import askopenfilename
import paramiko
if __name__ == '__main__':
root = Tk()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.2.34', username='pi', password='raspberry')
name1= askopenfilename(title = "Select File For Removal", filetypes = [("Video Files","*.h264")])
stdin, stdout, stderr = client.exec_command('ls -l')
for line in stdout:
print '... ' + line.strip('\n')
client.close()
Haha, hello again!
It's not possible to use a tkinter's file dialogs to list (or select) files on remote machine. You would need to mount the remote machine's drive using, for example, SSHFS (as mentioned in the question's comment), or use a custom tkinter dialog which displays the remote files list (that is in the stdout variable) and lets you choose the one.
You can write a dialog window yourself, here's a quick demo:
from Tkinter import *
def double_clicked(event):
""" This function will be called when a user double-clicks on a list element.
It will print the filename of the selected file. """
file_id = event.widget.curselection() # get an index of the selected element
filename = event.widget.get(file_id[0]) # get the content of the first selected element
print filename
if __name__ == '__main__':
root = Tk()
files = ['file1.h264', 'file2.txt', 'file3.csv']
# create a listbox
listbox = Listbox(root)
listbox.pack()
# fill the listbox with the file list
for file in files:
listbox.insert(END, file)
# make it so when you double-click on the list's element, the double_clicked function runs (see above)
listbox.bind("<Double-Button-1>", double_clicked)
# run the tkinter window
root.mainloop()
The easiest solution without a tkinter is - you could make the user type the filename using the raw_input() function.
Kind of like that:
filename = raw_input('Enter filename to delete: ')
client.exec_command('rm {0}'.format(filename))
So the user would have to enter the filename that is to be deleted; then that filename gets passed directly to the rm command.
It's not really a safe approach - you should definitely escape the user's input. Imagine what if the user types '-rf /*' as a filename. Nothing good, even if you're not connected as a root.
But while you're learning and keeping the script to yourself I guess it's alright.
I am working on python and biopython right now. I have a file upload form and whatever file is uploaded suppose(abc.fasta) then i want to pass same name in execute (abc.fasta) function parameter and display function parameter (abc.aln). Right now i am changing file name manually, but i want to have it automatically.
Workflow goes like this.
----If submit is not true then display only header and form part
--- if submit is true then call execute() and get file name from form input
--- Then displaying result file name is same as executed file name but only change in extension
My raw code is here -- http://pastebin.com/FPUgZSSe
Any suggestions, changes and algorithm is appreciated
Thanks
You need to read the uploaded file out of the cgi.FieldStorage() and save it onto the server. Ususally a temp directory (/tmp on Linux) is used for this. You should remove these files after processing or on some schedule to clean up the drive.
def main():
import cgi
import cgitb; cgitb.enable()
f1 = cgi.FieldStorage()
if "dfile" in f1:
fileitem = f1["dfile"]
pathtoTmpFile = os.path.join("path/to/temp/directory", fileitem.filename)
fout = file(pathtoTmpFile, 'wb')
while 1:
chunk = fileitem.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
execute(pathtoTmpFile)
os.remove(pathtoTmpFile)
else:
header()
form()
This modified the execute to take the path to the newly saved file.
cline = ClustalwCommandline("clustalw", infile=pathToFile)
For the result file, you could also stream it back so the user gets a "Save as..." dialog. That might be a little more usable than displaying it in HTML.