I am learning python and PySimpleGUI seems like a good start for exercises. With this self-exercise I'm working on, I would like to view and edit a YAML file. So far, I am able to create a prompt to browse and select a yaml. I am able to print the data in the console. But my next step is to view the yaml view PySimpleGUI window. I will work on how to edit the yaml content once I can figure out how to display it.
Here is my code:
import PySimpleGUI as sg
import yaml
from yaml.loader import SafeLoader
import os
working_directory = os.getcwd()
layout = [
[sg.Text("Shoose your yaml file:")],
[sg.InputText(key="-FILE_PATH-"),
sg.FileBrowse(initial_folder=working_directory, file_types=[("YAML Files","*.yaml")])],
[sg.Button("Submit"), sg.Exit()],
[sg.Multiline(size=(30,5), key= data)]
]
window = sg.Window("File Loader", layout).Finalize()
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
elif event == "Submit":
file_path = values["-FILE_PATH-"];
with open(file_path) as f:
data = yaml.load(f, Loader=SafeLoader)
# print(data)
print(values[data])
window.close()
Running this code i get this error:
Traceback (most recent call last):
File "yaml_gui.py", line 13, in <module>
[sg.Multiline(size=(30,5), key= data)]
NameError: name 'data' is not defined
I'm stuck because I am not sure why it is returning this error. The code works if I decide to just print the results in my terminal by using print(data). But when I use print(values[data]), it doesn't work.
Related
I work with a Mac. I have been trying to make a multiple sequence alignment in Python using Muscle. This is the code I have been running:
from Bio.Align.Applications import MuscleCommandline
cline = MuscleCommandline(input="testunaligned.fasta", out="testunaligned.aln", clwstrict=True)
print(cline)
from Bio import AlignIO
align = AlignIO.read(open("testunaligned.aln"), "clustal")
print(align)
I keep getting the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'testunaligned.aln'
Does anyone know how I could fix this? I am very new to Python and computer science in general, and I am totally at a loss. Thanks!
cline in your code is an instance of MuscleCommandline object that you initialized with all the parameters. After the initialization, this instance can run muscle, but it will only do that if you call it. That means you have to invoke cline()
When you simply print the cline object, it will return a string that corresponds to the command you can manually run on the command line to get the same result as when you invoke cline().
And here the working code:
from Bio.Align.Applications import MuscleCommandline
cline = MuscleCommandline(
input="testunaligned.fasta",
out="testunaligned.aln",
clwstrict=True
)
print(cline)
cline() # this is where mucle runs
from Bio import AlignIO
align = AlignIO.read(open("testunaligned.aln"), "clustal")
print(align)
While using time based rotating file handler.Getting error
os.rename('logthred.log', dfn)
WindowsError: [Error 32] The process cannot access the file because it
is being used by another process
config :
[loggers]
keys=root
[logger_root]
level=INFO
handlers=timedRotatingFileHandler
[formatters]
keys=timedRotatingFormatter
[formatter_timedRotatingFormatter]
format = %(asctime)s %(levelname)s %(name)s.%(functionname)s:%(lineno)d %
(output)s
datefmt=%y-%m-%d %H:%M:%S
[handlers]
keys=timedRotatingFileHandler
[handler_timedRotatingFileHandler]
class=handlers.TimedRotatingFileHandler
level=INFO
formatter=timedRotatingFormatter
args=('D:\\log.out', 'M', 2, 0, None, False, False)
Want to achieve time based rotating file handler and multiple process can write same log file.In python,I didn't find any thing which can help to resolve this issue.
I have read discussion on this issue (python issues).
Any suggestion which can resolve this issue.
Found the solution : Problem in Python 2.7 whenever we create child Process then file handles of parent process also inherited by child process so this is causing error. We can block this inheritance using this code.
import sys
from ctypes import windll
import msvcrt
import __builtin__
if sys.platform == 'win32':
__builtin__open = __builtin__.open
def __open_inheritance_hack(*args, **kwargs):
result = __builtin__open(*args, **kwargs)
handle = msvcrt.get_osfhandle(result.fileno())
if filename in args: # which filename handle you don't want to give to child process.
windll.kernel32.SetHandleInformation(handle, 1, 0)
return result
__builtin__.open = __open_inheritance_hack
I am trying to set my image to a file, but when i run it i get
Exception in Tkinter callback Traceback (most recent call last):
File
"C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py",
line 1699, in call
return self.func(*args) File "C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\turtle.py",
line 686, in eventfun
fun() File "C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\RPG.py",
line 20, in up
combat() File "C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\RPG.py",
line 57, in combat
enemy.shape(image) File "C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\turtle.py",
line 2777, in shape
self.turtle._setshape(name) File "C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\turtle.py",
line 2506, in _setshape
self._item = screen._createimage(screen._shapes["blank"]._data) File
"C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\turtle.py",
line 723, in _createimage
return self.cv.create_image(0, 0, image=image) File "", line 1, in create_image File
"C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py",
line 2483, in create_image
return self._create('image', args, kw) File "C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py",
line 2474, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: image "pyimage1" doesn't exist
when I have the file name clearly stated exactly where it is on my pc.
the code
import os
from turtle import Turtle,Screen
print(os.getcwd())
os.chdir('C:\\Users\\Travi\\Downloads')
screen.register_shape("Crawfish_attack.gif")
turtle = Turtle()
turtle.setimage("Crawfish_attack.gif")
thanks in advance
BTW the link is here
and the rest of the code all works and is not needed to be shown
Remove "\\Crawfish_attack" from the os.chdir() arguments. You need to path to the folder it is in, not the file. That is what the register_shape function will do is pull the exact file in that folder.
You were getting the error because you were trying to path to something (it was looking for a folder) that does not exist.
import os
from turtle import Turtle,Screen
print(os.getcwd())
os.chdir('C:\\Users\\Travi\\Downloads')
screen.register_shape("Crawfish_attack.gif")
The nub of the matter is, what am I doing wrong in the following code snippet?
from tkinter import *
from tkinter.ttk import *
root = Tk()
myButton = Button(root)
myImage = PhotoImage(myButton, file='myPicture.gif')
myButton.image = myImage
myButton.configure(image=myImage)
root.mainloop()
The error message I get from idle3 is as follows:
>>>
Traceback (most recent call last):
File "/home/bob/Documents/Python/tkImageTest.py", line 9, in <module>
myButton.configure(image=myImage)
File "/usr/lib/python3.2/tkinter/__init__.py", line 1196, in configure
return self._configure('configure', cnf, kw)
File "/usr/lib/python3.2/tkinter/__init__.py", line 1187, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
TypeError: __str__ returned non-string (type Button)
>>>
This error message has me stumped, I simply don't understand what it is trying to say. Any ideas?
I would also appreciate suggestions for changes...
The error seems to point to the myButton argument passed to PhotoImage. As you noted in your comment, PhotoImage was treating the widget object as a string (there are several options of type string; see a list of PhotoImage options here).
Your code will work if you implement that line without referencing the myButton object:
myImage = PhotoImage(file='myPicture.gif')
I'm not certain you need to alter the PhotoImage constructor. Look at the PhotoImage docs to determine the valid options (i.e. resource names) for that class. Quoting the help file:
Help on class PhotoImage in module tkinter:
class PhotoImage(Image)
| Widget which can display colored images in GIF, PPM/PGM format.
|
| Method resolution order:
| PhotoImage
| Image
| builtins.object
|
| Methods defined here:
|
| __getitem__(self, key)
| # XXX config
|
| __init__(self, name=None, cnf={}, master=None, **kw)
| Create an image with NAME.
|
| Valid resource names: data, format, file, gamma, height, palette,
| width.
FYI: The easiest way to get to the docs from Python at the command line or from IDLE:
from tkinter import PhotoImage
help(PhotoImage)
And lastly, another useful link about this class is at http://tkinter.unpythonic.net/wiki/PhotoImage.
I tested the example with python 2.7.9, 3.2.5, 3.3.5, 3.4.3 in 32bit and 64bit.
(Win 8.1 64bit)
The code works.
( in python 3.4.3 64bit I had first an error message.
I've completely uninstalled 3.4.3 and then reinstalled.
Now, the example works also with 3.4.3 64 bit )
# basic code from >>
# http://tkinter.unpythonic.net/wiki/PhotoImage
# extra code -------------------------------------------------------------------------
from __future__ import print_function
try:
import tkinter as tk
except:
import Tkinter as tk
import sys
import platform
print ()
print ('python ', sys.version)
print ('tkinter ', tk.TkVersion)
print ()
print (platform.platform(),' ',platform.machine())
print ()
# basic code -------------------------------------------------------------------------
root = tk.Tk()
def create_button_with_scoped_image():
# "w6.gif" >>
# http://www.inf-schule.de/content/software/gui/entwicklung_tkinter/bilder/w6.gif
img = tk.PhotoImage(file="w6.gif") # reference PhotoImage in local variable
button = tk.Button(root, image=img)
# button.img = img # store a reference to the image as an attribute of the widget
button.image = img # store a reference to the image as an attribute of the widget
button.grid()
create_button_with_scoped_image()
tk.mainloop()
I have already looked at and tried the resolutions to this question that others have posted. One user said that to try and change my setup.py file from:
from distutils.core import setup
import py2exe
setup(console=["dev.py"])
to
from distutils.core import setup
import py2exe
setup(service=["dev.py"])
I got the following results:
running py2exe
*** searching for required modules ***
Traceback (most recent call last):
File "C:\Python27\Scripts\distutils-setup.py", line 5, in <module>
setup(service=["C:\Python27\Scripts\dev.py"])
File "C:\Python27\lib\distutils\core.py", line 152, in setup
dist.run_commands()
File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands
self.run_command(cmd)
File "C:\Python27\lib\distutils\dist.py", line 972, in run_command
cmd_obj.run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 243, in run
self._run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 296, in _run
self.find_needed_modules(mf, required_files, required_modules)
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 1274, in
find_needed_modules
mf.import_hook(mod)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 719, in import_hook
return Base.import_hook(self,name,caller,fromlist,level)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 136, in import_hook
q, tail = self.find_head_package(parent, name)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 204, in find_head_package
raise ImportError, "No module named " + qname
ImportError: No module named dev
Now, when I run py2exe with "console" in my setup script it works fine, but the service doesn't start and I get the error. When I run py2exe with "service" in my setup script py2exe doesn't run and tells me it can't find my module.
I have tried to re-install py2exe to no resolution. I have also tried to change:
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
to
def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
Didn't make a difference either. CAN ANYONE HELP ME PLEASE? Here is what I am working on. It monitors a server and spits back a text file every 60 seconds which I use to monitor my servers at any given minute. Any help you guys and gals can give would be great.
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import wmi
import _winreg
from time import sleep
import os
class SrvMonSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "SrvMonSvc"
_svc_display_name_ = "Server Monitor"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
host = wmi.WMI(namespace="root/default").StdRegProv
try:
result, api = host.GetStringValue(
hDefKey = _winreg.HKEY_LOCAL_MACHINE,
sSubKeyName = "SOFTWARE\Server Monitor",
sValueName = "API")
if api == None:
raise Exception
else:
pass
except:
exit()
while 1 == 1:
with open("C:/test.txt", "wb") as b:
computer = wmi.WMI(computer="exsan100")
for disk in computer.Win32_LogicalDisk (DriveType=3):
name = disk.caption
size = round(float(disk.Size)/1073741824, 2)
free = round(float(disk.FreeSpace)/1073741824, 2)
used = round(float(size), 2) - round(float(free), 2)
for mem in computer.Win32_OperatingSystem():
a_mem = (int(mem.FreePhysicalMemory)/1024)
for me in computer.Win32_ComputerSystem():
t_mem = (int(me.TotalPhysicalMemory)/1048576)
u_mem = t_mem - a_mem
for cpu in computer.Win32_Processor():
load = cpu.LoadPercentage
print >>b, api
print >>b, name
print >>b, size
print >>b, used
print >>b, t_mem
print >>b, u_mem
print >>b, load
b.close()
date_list = []
stamp = time.strftime("%c",time.localtime(time.time()))
date_list.append(stamp)
name = re.sub(r"[^\w\s]", "",date_list[0])
os.rename("C:/test.txt", ("C:/%s.txt" % name))
try:
sleep(60.00)
except:
exit()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(SrvMonSvc)
Have you progressed from your original problem. I had similar problem with a python service and found out that it was missing DLLs since the 'System Path' (not the user path) was not complete.
Running pythonservice.exe with -debug from the command prompt was not a problem because it used correct PATH environment variable, but if your service is installed as a System service it's worth checking out if the System Path variable has all the paths for the required DLLs (MSVC, Python, System32). For me it was missing the python DLLs path, after that it worked again.