Play music in python with pygame creating a class [duplicate] - python

This question already has an answer here:
Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."
(1 answer)
Closed 1 year ago.
So i am creating a class that have to be called by other class and when i try it with the ide of pycharm it is working but with the console i am having some problems. (if it works with the ide it should not be problem of the path)
The class MySoundPygame:
import pygame as pygame
import time
class MySoundPygame:
def __init__(self, son):
#print("constructor")
self.son = son
pygame.mixer.pre_init(frequency=44100, size=-16, channels=1, buffer=512)
pygame.mixer.init()
self.sound1 = pygame.mixer.Sound(son)
def setSong(self, s):
try:
print(s)
self.sound1 = pygame.mixer.Sound(s)
self.sound1.play()
time.sleep(self.sound1.get_length())
res = {
'code': 200,
'message': 'ok'
}
return res
except:
res = {
'code': 500,
'message': 'Error'
}
return res
The general class that includes play music and other things, i am calling it with:
from .sound.MySoundPygame import MySoundPygame
song = MySoundPygame('/home/pi/Desktop/python/proyecto/audio/intro.mp3')
def putSoundTrack(self, nameSong):
print("entra")
res = song.setSong(nameSong)
print(res)
return res
But i get this error in console:
File "/home/pi/Desktop/python/proyecto/sound/MySoundPygame.py", line 13, in __init__
self.sound1 = pygame.mixer.Sound(son)
pygame.error: Unable to open file '/home/pi/Desktop/python/proyecto/audio/intro.mp3'
Thanks for the help!

[...] if it works with the ide it should not be problem of the path [...]
No, it is a problem with the path.
The path must be relative to the current working directory and not relative to the source (.py) file. In the IDE the current working directory is the same as the directory of the source files. This is not the case when you run it from the console.
One solution is to change the working directory at the begin of the application. See Could not open resource file: pygame.error: Couldn't open sprite/test_bg.jpg:
import os
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir)

Related

KeyError after build PySimpleGUI exe

I've trying to build exe for my PySimpleGui project. Problem is that when I start exe it give me error, but can't figure out why. Do I need to make some special magics when I use config.cfg file as my project folder root where project.py is?
File "project.py", line 46, in <module>
KeyError: 'CONF'
[21352] Failed to execute script 'project' due to unhandled exception!
My code related for line 46:
currentFile = __file__
realPath = os.path.realpath(currentFile)
dirPath = os.path.dirname(realPath)
dirName = os.path.basename(dirPath)
config = configparser.RawConfigParser()
config.read(dirPath + '/config.cfg')
def get_config_section():
if not hasattr(get_config_section, 'section_dict'):
get_config_section.section_dict = collections.defaultdict()
for section in config.sections():
get_config_section.section_dict[section] = dict(config.items(section))
return get_config_section.section_dict
config_dict = get_config_section()
# Values...
main_conf = config_dict['CONF']['key']
Did you run the code before compiling it ?
Do you have the latest version of pyinstaller installed.
Try running the code and seeing the error
Hope this helps :)

How to make pywin32 work with pyinstaller to make an executable?

I was trying to make a code where I had to change creation time of a file to creation time of another file (copying creation time from one file to another). I could find some answers about changing creation time on the following links and they work very well as well.
How do I change the file creation date of a Windows file?
Modify file create / access / write timestamp with python under windows
But when I try to put the code mentioned in an executable using pyinstaller it shows the following error:
AttributeError: 'pywintypes.datetime' object has no attribute 'astimezone'
How can I get over this error?
Below is the code which can be used to reproduce the situatuion
import pywintypes, win32file, win32con, ntsecuritycon
import os
def changeFileCTime(fname, createdNewtime):
wintime = pywintypes.Time(int(createdNewtime))
winfile = win32file.CreateFile(fname, ntsecuritycon.FILE_WRITE_ATTRIBUTES, 0, None, win32con.OPEN_EXISTING, 0, None)
win32file.SetFileTime(winfile, wintime, None, None)
winfile.close()
def main():
filename = input("File to copy creation time from: ")
ctime = os.path.getctime(filename)
filename = input("File to set ctime to: ")
changeFileCTime(filename, ctime)
if __name__ == '__main__':
main()
Versions of programs:
Python - 3.8.2
Pyinstaller - 4.1
pyinstaller code:
pyinstaller --onefile --console test.py
where test.py is the filename with the above code.

fatal python error (pygame parachute) Segmentation Fault when using Tkinter

I made small game in pygame and python 2.7 and added submit box with Tkinter.
It worked fine till I compiled it with py2exe / pygame2exe.
Compilation was error-free.
But when i clicked on exe file to launch the application, compiled-code threw this error:
fatal python error (pygame parachute) Segmentation Fault
This application has terminated in unusal way for more
information contact application support team.
When I delete Tkinter code and compile it it runs fine.
This is a part of Tkinter code:
#i tried importing both with import Tkinter and from Tkinter import*
if event.key==pygame.K_s:
subbox=Tkinter.Tk()
subbox_label=Tkinter.Label(subbox,text="Type your name:")
subbox_label.pack()
subbox_entry=Tkinter.Entry(subbox)
subbox_entry.pack()
def savescore(a):
a=str(a)
print a
print subbox_entry.get()
player_name=subbox_entry.get()
player_score=a
subbox_button=Tkinter.Button(text="Click",command=lambda:savescore(score))
subbox_button.pack()
subbox.mainloop()
UPDATE:
I kicked out Tkinter code line by line and it came up that importing Tkinter causes error!
That means that if I have just:
import Tkinter
my game won't work!!! What should I do?
setup file(pygame2exe but I may accidently delete something inside):
try:
from distutils.core import setup
import py2exe, pygame
from modulefinder import Module
import glob, fnmatch
import sys, os, shutil
import operator
except ImportError, message:
raise SystemExit, "Unable to load module. %s" % message
#hack which fixes the pygame mixer and pygame font
origIsSystemDLL = py2exe.build_exe.isSystemDLL # save the orginal before we edit it
def isSystemDLL(pathname):
# checks if the freetype and ogg dll files are being included
if os.path.basename(pathname).lower() in ("libfreetype-6.dll", "libogg-0.dll","sdl_ttf.dll"): # "sdl_ttf.dll" added by arit.
return 0
return origIsSystemDLL(pathname) # return the orginal function
py2exe.build_exe.isSystemDLL = isSystemDLL # override the default function with this one
class pygame2exe(py2exe.build_exe.py2exe): #This hack make sure that pygame default font is copied: no need to modify code for specifying default font
def copy_extensions(self, extensions):
#Get pygame default font
pygamedir = os.path.split(pygame.base.__file__)[0]
pygame_default_font = os.path.join(pygamedir, pygame.font.get_default_font())
#Add font to list of extension to be copied
extensions.append(Module("pygame.font", pygame_default_font))
py2exe.build_exe.py2exe.copy_extensions(self, extensions)
class BuildExe:
def __init__(self):
#Name of starting .py
self.script = "game_0.3.py"
#Name of program
self.project_name = "game"
#Project url
self.project_url = "it will be on sourceforge and indieDB"
#Version of program
self.project_version = "0.3"
#License of the program
self.license = "gnu gpl 2.0"
#Auhor of program
self.author_name = "John Doe "
self.author_email = "i dont want spam"
self.copyright = "John Doe 2014"
#Description
self.project_description = None
#Icon file (None will use pygame default icon)
self.icon_file = "icon.ico"
#Extra files/dirs copied to game
self.extra_datas = ["block.png","CHARACTER.png","icon.ico","COPYING.txt","README1.txt","name.txt","score.txt"]
#Extra/excludes python modules
self.extra_modules = []
self.exclude_modules =['AppKit', 'Foundation', 'Numeric', 'OpenGL.GL', '_scproxy', '_sysconfigdata', 'copyreg', 'dummy.Process', 'numpy', 'pkg_resources', 'queue', 'winreg', 'pygame.sdlmain_osx']
#DLL Excludes
self.exclude_dll = ['']
#python scripts (strings) to be included, seperated by a comma
self.extra_scripts = []
#Zip file name (None will bundle files in exe instead of zip file)
self.zipfile_name =None
#Dist directory
self.dist_dir ='dist'
## Code from DistUtils tutorial at http://wiki.python.org/moin/Distutils/Tutorial
## Originally borrowed from wxPython's setup and config files
def opj(self, *args):
path = os.path.join(*args)
return os.path.normpath(path)
def find_data_files(self, srcdir, *wildcards, **kw):
# get a list of all files under the srcdir matching wildcards,
# returned in a format to be used for install_data
def walk_helper(arg, dirname, files):
if '.svn' in dirname:
return
names = []
lst, wildcards = arg
for wc in wildcards:
wc_name = self.opj(dirname, wc)
for f in files:
filename = self.opj(dirname, f)
if fnmatch.fnmatch(filename, wc_name) and not os.path.isdir(filename):
names.append(filename)
if names:
lst.append( (dirname, names ) )
file_list = []
recursive = kw.get('recursive', True)
if recursive:
os.path.walk(srcdir, walk_helper, (file_list, wildcards))
else:
walk_helper((file_list, wildcards),
srcdir,
[os.path.basename(f) for f in glob.glob(self.opj(srcdir, '*'))])
return file_list
def run(self):
if os.path.isdir(self.dist_dir): #Erase previous destination dir
shutil.rmtree(self.dist_dir)
#Use the default pygame icon, if none given
if self.icon_file == None:
path = os.path.split(pygame.__file__)[0]
self.icon_file = os.path.join(path, 'pygame.ico')
#List all data files to add
extra_datas = []
for data in self.extra_datas:
if os.path.isdir(data):
extra_datas.extend(self.find_data_files(data, '*'))
else:
extra_datas.append(('.', [data]))
setup(
cmdclass = {'py2exe': pygame2exe},
version = self.project_version,
description = self.project_description,
name = self.project_name,
url = self.project_url,
author = self.author_name,
author_email = self.author_email,
license = self.license,
# targets to build
console = [{
'script': self.script,
'icon_resources': [(0, self.icon_file)],
'copyright': self.copyright
}],
options = {'py2exe': {'optimize': 2, 'bundle_files': 1, 'compressed': True, \
'excludes': self.exclude_modules, 'packages': self.extra_modules, \
'dll_excludes': self.exclude_dll,
'includes': self.extra_scripts} },
zipfile = self.zipfile_name,
data_files = extra_datas,
dist_dir = self.dist_dir
)
if os.path.isdir('build'): #Clean up build dir
shutil.rmtree('build')
if __name__ == '__main__':
if operator.lt(len(sys.argv), 2):
sys.argv.append('py2exe')
BuildExe().run() #Run generation
raw_input("Press any key to continue") #Pause to let user see that things ends
another important thing:if i import Tkinter before pygame there is no segmentation error but game doesn't run and error window pops out and says this application requested runtime to terminate in unusal way for more information contact app support
Did you check py2exe/Bugs?
While it is not exactly the same crash, the root-cause, related to Tkinter internal dependence on sub-layer of Tcl & Tk DLL services seems similar:
cit.:
"""
Using Tkinter, and bundle_files = 1, i get an immediate crash.
Here's my setup:
winxp sp2
py2exe 0.6.8
python 2.5.1
My test file is "example.py", as follows:
#### start
from Tkinter import *
if __name__ == '__main__':
print "hello"
#### end
my setup.py is as follows:
#### start
from distutils.core import setup
import py2exe
setup(
options = {'py2exe': {'bundle_files': 1}},
zipfile = None,
console=['example.py'])
#### end
it compiles just fine, but when running the "example.exe" that is produced in the "dist" directory, it immediately gets the error message "example.exe has encountered a problem and needs to close. We are sorry for the inconvenience".
Using the same setup.py, but with bundle_files = 3 works fine; using bundle_files = 2 causes the same crash.
I hope this is sufficient information to replicate this bug. I will be happy to provide any other info if you need it - just post back here.
"""
+ a there proposed workaround:
cit.:
"""
I "fixed" this by editing site-packages/py2exe/build_exe.py,
adding "tcl85.dll" and"tk85.dll" to the "dlls_in_exedir" list
-- meaning that they get put next to the .exe rather than bundled inside it.
Slightly messy, but much better than bundled=3
"""

.py file works, converted .exe file doesn't

EDIT: Turns out the actual error was with the font code - Apparently I had to use
pygame.font.SysFont("some_font", font_size)
instead of
pygame.font.Font(None, font_size)
everywhere in my original piece of code.
Consider this question resolved.
I've made a game with pygame and want it to run on computers without Python and Pygame, for which matter I got py2exe and shamelessly copied the pygame2exe code found here, adjusting it for my file's name and that kind of stuff...
The conversion (I tried both the windows cmd thingy and actual Python, both with the same results) was successful, and when I run the executable file I get a black window without the actual background, the only thing I saw that it worked were the icon and title of the window which were integrated in the Python code. Afterwards I immediately get this error message:
Runtime error! This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
Since the icon was displayed at the top left of the window (which it also has to load an image for) and the background didn't appear, the error was most likely somewhere in between the following few lines, if it's due to some problem in the actual code (although it works in IDLE). There I do the following things:
Defining variables for images, then defining another variable as that variable so it's a copy of it, so the game works faster
Loading sound effects and setting their volume
Setting background music, it's volume and making it on loop
Following that, these are the lines of code up until the setting of the background image.
running = True
game = 0
clock = pygame.time.Clock()
FPS = 150
name = ""
while running==True:
screen.fill(0)
clock.tick(FPS)
for x in range(width/background.get_width()+1):
for y in range(height/background.get_height()+1):
screen.blit(background,(x*200,y*200))
For reference, this is the code of setup.py (although I doubt that's the problem anyway:
try:
from distutils.core import setup
import py2exe, pygame
from modulefinder import Module
import glob, fnmatch
import sys, os, shutil
import operator
except ImportError, message:
raise SystemExit, "Unable to load module. %s" % message
#hack which fixes the pygame mixer and pygame font
origIsSystemDLL = py2exe.build_exe.isSystemDLL # save the orginal before we edit it
def isSystemDLL(pathname):
# checks if the freetype and ogg dll files are being included
if os.path.basename(pathname).lower() in ("libfreetype-6.dll", "libogg- 0.dll","sdl_ttf.dll"): # "sdl_ttf.dll" added by arit.
return 0
return origIsSystemDLL(pathname) # return the orginal function
py2exe.build_exe.isSystemDLL = isSystemDLL # override the default function with this one
class pygame2exe(py2exe.build_exe.py2exe): #This hack make sure that pygame default font is copied: no need to modify code for specifying default font
def copy_extensions(self, extensions):
#Get pygame default font
pygamedir = os.path.split(pygame.base.__file__)[0]
pygame_default_font = os.path.join(pygamedir, pygame.font.get_default_font())
#Add font to list of extension to be copied
extensions.append(Module("pygame.font", pygame_default_font))
py2exe.build_exe.py2exe.copy_extensions(self, extensions)
class BuildExe:
def __init__(self):
#Name of starting .py
self.script = "test.py"
#Name of program
self.project_name = "test"
#Project url
self.project_url = "about:none"
#Version of program
self.project_version = "0.9"
#License of the program
self.license = "No license"
#Auhor of program
self.author_name = "Me"
self.author_email = "example#example.com"
self.copyright = "Copyright (c) 2009 Me."
#Description
self.project_description = "Test"
#Icon file (None will use pygame default icon)
self.icon_file = None
#Extra files/dirs copied to game
self.extra_datas = ["spiel"]
#Extra/excludes python modules
self.extra_modules = []
self.exclude_modules = []
#DLL Excludes
self.exclude_dll = ['']
#python scripts (strings) to be included, seperated by a comma
self.extra_scripts = []
#Zip file name (None will bundle files in exe instead of zip file)
self.zipfile_name = None
#Dist directory
self.dist_dir ='dist'
## Code from DistUtils tutorial at http://wiki.python.org/moin/Distutils/Tutorial
## Originally borrowed from wxPython's setup and config files
def opj(self, *args):
path = os.path.join(*args)
return os.path.normpath(path)
def find_data_files(self, srcdir, *wildcards, **kw):
# get a list of all files under the srcdir matching wildcards,
# returned in a format to be used for install_data
def walk_helper(arg, dirname, files):
if '.svn' in dirname:
return
names = []
lst, wildcards = arg
for wc in wildcards:
wc_name = self.opj(dirname, wc)
for f in files:
filename = self.opj(dirname, f)
if fnmatch.fnmatch(filename, wc_name) and not os.path.isdir(filename):
names.append(filename)
if names:
lst.append( (dirname, names ) )
file_list = []
recursive = kw.get('recursive', True)
if recursive:
os.path.walk(srcdir, walk_helper, (file_list, wildcards))
else:
walk_helper((file_list, wildcards),
srcdir,
[os.path.basename(f) for f in glob.glob(self.opj(srcdir, '*'))])
return file_list
def run(self):
if os.path.isdir(self.dist_dir): #Erase previous destination dir
shutil.rmtree(self.dist_dir)
#Use the default pygame icon, if none given
if self.icon_file == None:
path = os.path.split(pygame.__file__)[0]
self.icon_file = os.path.join(path, 'pygame.ico')
#List all data files to add
extra_datas = []
for data in self.extra_datas:
if os.path.isdir(data):
extra_datas.extend(self.find_data_files(data, '*'))
else:
extra_datas.append(('.', [data]))
setup(
cmdclass = {'py2exe': pygame2exe},
version = self.project_version,
description = self.project_description,
name = self.project_name,
url = self.project_url,
author = self.author_name,
author_email = self.author_email,
license = self.license,
# targets to build
windows = [{
'script': self.script,
'icon_resources': [(0, self.icon_file)],
'copyright': self.copyright
}],
options = {'py2exe': {'optimize': 2, 'bundle_files': 1, 'compressed': True, \
'excludes': self.exclude_modules, 'packages': self.extra_modules, \
'dll_excludes': self.exclude_dll,
'includes': self.extra_scripts} },
zipfile = self.zipfile_name,
data_files = extra_datas,
dist_dir = self.dist_dir
)
if os.path.isdir('build'): #Clean up build dir
shutil.rmtree('build')
if __name__ == '__main__':
if operator.lt(len(sys.argv), 2):
sys.argv.append('py2exe')
BuildExe().run() #Run generation
raw_input("Press any key to continue") #Pause to let user see that things ends
Further information:
OS: Windows 7, 32 bit
Pygame version: 1.9.2. (I think - it's the latest version)
Python version: 2.7.6.
Py2exe version: Whatever the latest one was
I never actually had a msvcr90.dll file version 9.0.21022.8, like the py2exe tutorial specifically recommends to use. I now have msvcr71.dll, msvcr100.dll, msvcr100_clr0400.dll and msvcr110_clr0400.dll (intended for this OS) instead, which was what seemed to be available from microsoft packages. Is it possible that represents the problem? If so, where the hell can I get the correct file from? I tried looking it up, but there didn't seem to be any download link for it (at least not that it gives me the exact file I want now).
And if not, do you know where else the problem could be?
msvcr90.dll comes along with Microsoft Visual C++ 2008 runtimes. Grab the version for your architecture, install and try again. Here is the x86 version and here is the x64 version.

Python - create object of class from one package in different package

I started using Python few days back and I think I have a very basic question where I am stuck. Maybe I am not doing it correctly in Python so wanted some advice from the experts:
I have a config.cfg & a class test in one package lib as follows:
myProj/lib/pkg1/config.cfg
[api_config]
url = https://someapi.com/v1/
username=sumitk
myProj/lib/pkg1/test.py
class test(object):
def __init__(self, **kwargs):
config = ConfigParser.ConfigParser()
config.read('config.cfg')
print config.get('api_config', 'username')
#just printing here but will be using this as a class variable
def some other foos()..
Now I want to create an object of test in some other module in a different package
myProj/example/useTest.py
from lib.pkg1.test import test
def temp(a, b, c):
var = test()
def main():
temp("","","")
if __name__ == '__main__':
main()
Running useTest.py is giving me error:
...
print config.get('api_config', 'username')
File "C:\Python27\lib\ConfigParser.py", line 607, in get
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'api_config'
Now if I place thie useTest.py in the same package it runs perfectly fine:
myProj/lib/pkg1/useTest.py
myProj/lib/pkg1/test.py
myProj/lib/pkg1/config.cfg
I guess there is some very basic package access concept in Python that I am not aware of or is there something I am doing wrong here?
The issue here is that you have a different working directory depending on which module is your main script. You can check the working directory by adding the following lines to the top of each script:
import os
print os.getcwd()
Because you just provide 'config.cfg' as your file name, it will attempt to find that file inside of the working directory.
To fix this, give an absolute path to your config file.
You should be able to figure out the absolute path with the following method since you know that config.cfg and test.py are in the same directory:
# inside of test.py
import os
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'config.cfg')

Categories