Cx_Freeze compiled pygame file doesn't work - python-3.x

The following error happens if i try to compile my python (using python 3.2) file:
Traceback(most recent call last):
File
"c:\python32\lib\site-packages\cx_Freeze\initscripts\Console3.py", line
27, in <module>
exec(code, m.__dict__)
File "Abertura.py", line 208, in <module>
File "Abertura.py", line 154, in main
File "Abertura.py", line 9, in __init__
pygame.error: Couldn't open
C:\Python32\build\exe.win32-3.2\library.zip\Imagens\menu1.png
I already included pygame._view and tried to copy the 'Imagens' directory to the library.zip file, but it doesn't work. I'm using images, musics and videos that come's from other directories by including in my code:
def file_path(filename, directory):
return os.path.join(
os.path.dirname(os.path.abspath(__file__)),
directory,
filename
)
And this is my setup.py file:
from cx_Freeze import setup, Executable
exe=Executable(
script="Abertura.py",
base="Win32Gui",
)
includefiles=[('C:\Python32\Imagens', 'Imagens'),
('C:\Python32\Musicas','Musicas'),
('C:\Python32\Videos','Videos')
]
includes=[]
excludes=[]
packages=[]
setup(
version = "1.0",
description = "RPG",
author = "Pedro Forli e Ivan Veronezzi",
name = "Batalha Inapropriada",
options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}},
executables = [exe]
)
How do i fix it?
(sorry about my possibles english mistakes)

Anything accessed from within a compressed archive (such as zips, rars, tar.gzs, etc...) need to be decompressed first before you access them.
That being said, you should not have your recourse files in a zip because decompressing it every time to want to access something is slow, and difficult. Your resource files should be in a normal directory, not an archive.
The reason why you're getting this error is because it's looking for a folder named library.zip and it's not finding one because library.zip is not a folder, it's a file.
How I would suggest to combat this error is to extract everything into a folder named library and to change in your code anywhere that library.zip exists to library.

Related

Python FileNotFoundError even if the File is there

My project directory tree is something like this,
build
----fonts
--------Roboto Bold.ttf
----main.py
The following code errors out,
from pyglet import font
font.add_file("fonts\\Roboto Bold.ttf")
Also tried this code,
import os
from pyglet import font
font.add_file(str(os.getcwd())+"\\fonts\\Roboto Bold.ttf")
the error is,
Traceback (most recent call last):
File "{full_dir_name}\build\main.py", line 25, in <module>
font.add_file(str(os.getcwd())+'\\fonts\\Roboto Bold.ttf')
File "C:\python-3.8.5-amd64\lib\site-packages\pyglet\font\__init__.py", line 183, in add_file
font = open(font, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '{full_dir_name}\\fonts\\Roboto Bold.ttf'
I have tried about a day now and also seen other posts here but could not resolve...
The resource (image, font, sound, etc.) file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd(). If the file is in an subfolder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()) the relative filepath. e.g.:
font.add_file(str(os.getcwd())+"\\fonts\\Roboto Bold.ttf")
font.add_file(os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts/Roboto Bold.ttf"))

pdfkit [WinError 740] The requested operation requires elevation python3

I would like to convert an HTML page into a PDF file, based on the given URL. I have tried pdfkit, but it throws the following error:
[WinError 740] The requested operation requires elevation.
Code:
import pdfkit
path_wkthmltopdf = "D:\\w.exe"
config = pdfkit.configuration(wkhtmltopdf = path_wkthmltopdf )
pdfkit.from_url("http://www.google.com", 'd:\\out.pdf', configuration=config)
Output error:
n [42]: import pdfkit
path_wkthmltopdf = "D:\\w.exe"
config = pdfkit.configuration(wkhtmltopdf = path_wkthmltopdf )
pdfkit.from_url("http://www.google.com", 'd:\\out.pdf', configuration=config)
Traceback (most recent call last):
File "<ipython-input-42-58323936ac63>", line 5, in <module>
pdfkit.from_url("http://www.google.com", 'd:\\out.pdf', configuration=config)
File "C:\Users\31081\AppData\Local\conda\conda\envs\ml\lib\site-packages\pdfkit\api.py", line 26, in from_url
return r.to_pdf(output_path)
File "C:\Users\31081\AppData\Local\conda\conda\envs\ml\lib\site-packages\pdfkit\pdfkit.py", line 129, in to_pdf
stderr=subprocess.PIPE)
File "C:\Users\31081\AppData\Local\conda\conda\envs\ml\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 143, in __init__
super(SubprocessPopen, self).__init__(*args, **kwargs)
File "C:\Users\31081\AppData\Local\conda\conda\envs\ml\lib\subprocess.py", line 729, in __init__
restore_signals, start_new_session)
File "C:\Users\31081\AppData\Local\conda\conda\envs\ml\lib\subprocess.py", line 1017, in _execute_child
startupinfo)
OSError: [WinError 740] The requested operation requires elevation
I encountered with this problem too, I solved it by running .exe after run this it will create new dir, go inside this dir then bin dir you will find a exe file there like
C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe
So, replace "D:\w.exe" to above kind of path in your code then it will work
Cause
You are most likely getting that error as a result of downloading the Installer version, but not installig it. Thus, when running your code with wkhtmltopdf in the configuration pointing to that executable (which requires elevation of privilege), you get the following error:
OSError: [WinError 740] The requested operation requires elevation
Solution
You could install wkhtmltopdf by running that Installer version and choosing the destination folder (let's say C:\Program Files). You will find the wkhtmltopdf.exe file that you need to add to your configuration inside the bin folder. Hence, you should use as follows:
config = pdfkit.configuration(wkhtmltopdf=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')
pdfkit.from_url('http://google.com', 'out.pdf', configuration=config)
Another solution would be to download the 7z Archive version, extract the files, in which you'll find wkhtmltopdf.exe under the bin folder as well.
I ran into this issue when I had not gone through the full installation of the wkpdftohtml library. Once it was unpacked, this ran without need for elevation.

[ Python 2.7 ]Package program with Pynsist

I am packaging a Python 2.7 program with the lastest version of Pynsist.
I've created an installer.cfg file following this example.
But when I try to package my application running
pynsist installer.cgf
into the application folder it comes up with
Copying Python installer to build directory
PyLauncher MSI already in build directory.
Copying packages into build directory...
Traceback (most recent call last):
File "/usr/local/bin/pynsist", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/nsist/__init__.py", line 540, in main
InstallerBuilder(**args).run(makensis=(not options.no_makensis))
File "/usr/local/lib/python2.7/dist-packages/nsist/__init__.py", line 495, in run
self.prepare_packages()
File "/usr/local/lib/python2.7/dist-packages/nsist/__init__.py", line 381, in prepare_packages
py_version=self.py_version, exclude=self.exclude)
File "/usr/local/lib/python2.7/dist-packages/nsist/copymodules.py", line 224, in copy_modules
mc.copy(modname, target, exclude)
File "/usr/local/lib/python2.7/dist-packages/nsist/copymodules.py", line 195, in copy
check_package_for_ext_mods(path, self.py_version)
File "/usr/local/lib/python2.7/dist-packages/nsist/copymodules.py", line 41, in check_package_for_ext_mods
check_ext_mod(os.path.join(path, dirpath, filename), target_python)
File "/usr/local/lib/python2.7/dist-packages/nsist/copymodules.py", line 30, in check_ext_mod
raise ExtensionModuleMismatch(extensionmod_errmsg % ('Windows', path))
nsist.copymodules.ExtensionModuleMismatch: Found an extension module that will not be usable on Windows:
/usr/lib/python2.7/dist-packages/pygame/rwobject.so
Put Windows packages in pynsist_pkgs/ to avoid this.
So the problem I think is with Pygame.
On Google there in nothing about this, but i cannot use others programs for packaging(eg. py2exe, pyinstaller ecc...).
Thanks and sorry for the bad english
Reposting as an answer, since it worked:
If you put pygame in packages=, it tries to copy it from your computer. But on your computer that's pygame for Linux, which won't work on Windows. If you instead put pygame in the pypi_wheels= bit of the config file, Pynsist will take care of downloading a Windows version for you.
Have a look at the pygame example in the Pynsist repository.
Most packages don't have this problem because they only contain Python code, which is the same files on all platforms. Pygame has compiled modules, which have to be compiled for the right platform.

Programmatically import Python files as modules within another Python file and run them

There's a highly upvoted StackOverflow thread which says that the best way to run Python files within another Python file is to import them as a module.
That works well for me, except that I'm having trouble doing it programmatically in a case where there are at least hundreds (if not thousands) of files to be run.
All of the files are in the same directory and share a common naming convention. I tried to run them like this:
import glob, os
for filename in glob.glob("*_decomp*"):
import filename
but that throws an error:
Traceback (most recent call last):
File "C:\Python35\lib\site-packages\IPython\core\interactiveshell.py", line
3066, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "", line 4, in
import filename
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.1.3\helpers\pydev_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
ImportError: No module named 'filename'
The variable filename is also underlined in red in the IDE, which negates my original hypothesis that it was simply a matter of needing to remove the .py file extension.
This works fine for printing:
import glob, os
for filename in glob.glob("*_decomp*"):
# import filename
print(filename)
So I'm not really sure what the problem with the earlier statement is or how to work around it. I can also do the import manually and that works fine, but again I'd like to do it programmatically so that I don't have to type all of the file names and because the file names will change over time.
Finally, I also tried it with [:-3] (i.e. filename[:-3]) to remove the file extension, but again that only works for print() and not import.
There are other ways of importing not covered by the SO link you give, for example (although I'm not holding this up as a canonical or even necessarily good way of importing, but it works for me) based on one of the examples I found via this SO question/answers Building a minimal plugin architecture in Python I wrote a simple plugin implementation below - it searches a folder called 'plugins' below wherever the .py file with this in it is. Each plugin has to implement a class called Plugin, they all get the same parameters.
path = 'plugins'
# find subdirs of the path - these are the groups
# for each group, load all the .py files, each provides one or more actions
searchdir = os.path.join(os.path.split(__file__)[0],path)
if os.access(searchdir, os.F_OK):
print "searchdir=",searchdir
print "results=",os.walk(searchdir)
(root, dirs, files) =os.walk(searchdir).next()
print root,dirs,files
for dir in dirs:
print "scanning dir",dir
self.groups[dir] = []
sys.path.insert(0, os.path.join(root,dir))
for f in sorted(os.listdir(os.path.join(root,dir))):
print "looking at",f
fname, ext = os.path.splitext(f)
if ext == '.py':
print "importing ",f
mod = __import__(fname)
try:
self.groups[dir].append(mod.PlugIn(group,cmdobj,config, jts_data, directives, current_config_props,allcomponents,globals))
except:
print "URGH! plugin instantiation error!"
raise
sys.path.pop(0)
else:
print "############# no plugins folder",searchdir

Accessing files in directory outside of Anaconda

Newb here to python/anaconda.
I'm trying to run a python script (and it reads other files local to its directory) which doesn't belong to the same directory as the Anaconda directory where I'm executing the python command there.
So I am trying to run a python script (lets say it resides in path B directory) from the Anaconda python (say path A directory). Within this script, there is a call to reading a local file so we have only the fileName.py and then the command prompt spits out this error:
C:\Users\usernameABC\Anaconda3>python C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py
Traceback (most recent call last):
File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 165, in <module>
main()
File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 130, in main
resp = ReadFemResp()
File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 27, in ReadFemResp
dct = thinkstats2.ReadStataDct(dct_file)
File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\thinkstats2.py", line 2646, in ReadStataDct
for line in open(dct_file, **options):
FileNotFoundError: [Errno 2] No such file or directory: '2002FemResp.dct'
I basically just want to run the script, whether its in Anaconda or wherever is the easiest or most natural that most experienced coders would. Please help! Thanks in advance for feedback!
You can change your current working directory using the
cd (change directory) command
You can also modify the script so that you can specify where the files are that you want to access. If you show us the script that you are running we may be able to help more.

Resources