Python, PySerial and cx-freeze - python-3.x

Trying to learn cx-freeze. I have a python program that I am trying freeze to exe.
I use PySerial and no matter how I try to include win32 nothing seems to help. I use Python 3.2 and win7.
I have searched the web thin, and others have had the same problem, but no solution seems to be appearing. But I doubt that no one have succeeded in cx_freezing something that uses PySerial.
I am completely stuck. Any help would be much appreciated
Error:
Traceback (most recent call last):
File "C:\Python32\lib\site-packages\
7, in <module>
exec(code, m.__dict__)
File "snapper.py", line 8, in
File "C:\Python32\lib\site-packages\
from serial.serialwin32 import *
File "C:\Python32\lib\site-packages\
e>
from serial import win32
ImportError: cannot import name win32
Setup.py:
from cx_Freeze import setup,Executable
includefiles = ['caml.pkl', 'seql.pkl']
includes = ['DataBase', 'serial.win32']
excludes = ['Tkinter']
packages = []
setup(
name = 'Setup',
version = '0.1',
description = 'Snapper configuration utility',
author = 'LST',
author_email = 'info#-.com',
options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}},
executables = [Executable('snapper.py')]
)
Any idea where to go from here?
Thanks in advance
I tried to do a blind import:
if False:
import serial.win32
no luck...
Maybe i am looking at this the wrong way....

Okay, problem solved.
You need to use packages to force cx_Freeze to include serial.win32 (not "include")
Following line works:
packages = ['serial.win32']
Memo to my self and others: Be sure to check the dist folder for actually included packages. I have no idea why all packages didn't get included by cx_Freeze in the first place, but this works for me.

If you can use a different tool to freeze your program, PyInstaller says it supports PySerial.

Related

Unable to use .exe frozen with cx_Freeze on another pc with the following error related to rpy2

I created a small program with rpy2 to import R in Python and packaged it with cx_Freeze. Then I tested it on my development PC. It works well. However, once I copy my .exe to another PC with a similar OS (Windows 10), the same python (3.7) and R version (3.5.2), the following error message jumps out:
Traceback(most recent call last):
File "D:\software\Python3.7.3\lib\site-
packages\cx_Freeze\initscripts\__startup__.py",line 14, in run
File "D:\software\Python3.7.3\lib\site-
packages\cx_Freeze\initscripts\Console.py",line 26, in run
File "TR_SNP.py", line 32, in <module>
File "D:\plot.py",line 23, in <module>
dplR = importr('dplR')
File "D:\software\Python3.7.3\lib\site-packages\rpy2\robjects\packages.py",line 453,in importr
rpy2.rinterface.RRuntimeError
It seems like something is wrong with the R lib import.
I tried to search for the answer. Here is one that I think would be similar to my problem: rpy2 works good in PyCharm and doesn't work in .exe file
However, that answer does not provide details like where I should put the R libs.
The frozen application probably does not look for the R installation at the right place on the target PC. Try to add the following lines to your main application:
import platform
import rpy2.situation
lib_path = rpy2.situation.get_rlib_path(r_home, platform.system())
print(lib_path)
This will display the location where the application is looking for the R lib. This path (and probably the whole r_home) should exist on the target PC and contain a compatible R installation.
If the path is wrong, you need to tell the frozen application where the R installation is located on the target machine using something like
import os
os.environ['R_HOME'] = path_to_r_home_on_target_machine
But this will be difficult as you will not know in general where the R installation is located. You could try to add the following lines to your application (not sure if it works):
import sys
import os
import rpy2.situation
if getattr(sys, 'frozen', False):
# The application is frozen
# reset R_HOME and try to find a R installation using the fallback mechanisms
del os.environ['R_HOME']
os.environ['R_HOME'] = rpy2.situation.get_r_home()

_pickle.PicklingError: args[0] from __newobj__ args has the wrong class in tensorflow project

code:
# Write vocabulary#
vocab_processor.save(os.path.join(checkpoint_dir, "vocab"))
Error:
Traceback (most recent call last):
File "train.py", line 145, in
vocab_processor.save(os.path.join(checkpoint_dir, "vocab"))
File "/home/chinu/.local/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/preprocessing/text.py", line 233, in save
f.write(pickle.dumps(self))
_pickle.PicklingError: args[0] from newobj args has the wrong class
I met the same problem as you. May be you can check this issue and the code changed in it helped me.
The detail in that pull request is to change the following code in preprocesss.py :
self.sup = super(MyVocabularyProcessor,self)
self.sup.__init__(max_document_length,min_frequency,vocabulary,tokenizer_fn)
into the next block.
sup = super(MyVocabularyProcessor,self)
sup.__init__(max_document_length,min_frequency,vocabulary,tokenizer_fn)
tips: Remember to use 2to3 -m filename tool to change other python2 files into python3 ones.
I had a look at the same project https://github.com/dhwajraj/deep-siamese-text-similarity - I had tried Python 3.x but this failed, had to change the Open file with encoding, change xrange to range etc and convert the code back - I ended up at the same issue as you. The code base is Python 2.x and after installing everything as indicated
numpy 1.11.0
tensorflow 1.2.1 (had to downgrade < 1.2 for Python2)
gensim 1.0.1
nltk 3.2.2

Zlib and binascii don't build with Python3.6

I've been trying to build Python3.6.1 from source code on Ubuntu 14.04. The sequence of commands is as recommended by README:
./configure
make
make test
The latter crashes because it cannot import binascii. In its output there is a following:
Following modules built successfully but were removed because they could not be imported:
binascii zlib
Trying to skip make test and start make install I have it crashing after failing to import zlib. Some folks in the Ubuntu forums suggested to update all the zlib's packages from repositories. That doesn't help. How do I fix this?
Try to install zlib from the source code(http://www.zlib.net/) manually (not via yum/apt-get/brew...) might be helpful.
I have tried the Python3.6.1 building in my mac dev and also encountered your problem. It complains following message after making.
Python build finished successfully!
The necessary bits to build these optional modules were not found:
... zlib ...
And I can't import zlib in interactive shell too.
>>> import zlib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'zlib'
I have solved the problem by the following steps.
visit http://www.zlib.net/ and download zlib-1.2.11.
install zlib (decompress, configure, make, make install).
reinstall Python3.6.1 (make clean, make).
I found the making process did not complain about zlib missing anymore and I could import zlib successfully in the shell.
Actually, to solve this kind of problems, we might find some hints from the source code.
We can find the following code in "setup.py" and the comments are pretty helpful. We can modify the code with debug information to locate where the problem really is (for me, it is because the first if check fails due to zlib.h missing).
# You can upgrade zlib to version 1.1.4 yourself by going to
# http://www.gzip.org/zlib/
zlib_inc = find_file('zlib.h', [], inc_dirs)
have_zlib = False
if zlib_inc is not None:
zlib_h = zlib_inc[0] + '/zlib.h'
version = '"0.0.0"'
version_req = '"1.1.3"'
if host_platform == 'darwin' and is_macosx_sdk_path(zlib_h):
zlib_h = os.path.join(macosx_sdk_root(), zlib_h[1:])
with open(zlib_h) as fp:
while 1:
line = fp.readline()
if not line:
break
if line.startswith('#define ZLIB_VERSION'):
version = line.split()[2]
break
if version >= version_req:
if (self.compiler.find_library_file(lib_dirs, 'z')):
if host_platform == "darwin":
zlib_extra_link_args = ('-Wl,-search_paths_first',)
else:
zlib_extra_link_args = ()
exts.append( Extension('zlib', ['zlibmodule.c'],
libraries = ['z'],
extra_link_args = zlib_extra_link_args))
have_zlib = True
else:
missing.append('zlib')
else:
missing.append('zlib')
else:
missing.append('zlib')

Mako: cannot import the Template class. Have a SyntaxError error in "\mako\template.py", line 622

I want to try Mako with Django instead of Django's default template language. But I'm having a problem when I try to import Mako's Template class as written in the manual:
from mako.template import Template
mytemplate = Template("hello world!")
print mytemplate.render()
I do this in Windows cmd and receive such an error:
C:\Documents and Settings\User>cd C:\py\project\vendor\template\Mako_73 // cd to where I unpacked Mako
C:\py\project\vendor\template\Mako_73>python // run Python interpreter
>>> from mako.template import Template // trying to import and getting an error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".\mako\template.py", line 622
exec code in module.__dict__, module.__dict__
^
SyntaxError: invalid syntax
The code from that part:
def _compile_text(template, text, filename):
identifier = template.module_id
source, lexer = _compile(template, text, filename,
generate_magic_comment=template.disable_unicode)
cid = identifier
if not util.py3k and isinstance(cid, unicode):
cid = cid.encode()
module = types.ModuleType(cid)
code = compile(source, cid, 'exec')
exec code in module.__dict__, module.__dict__
return (source, module)
What can it be? I couldn't find anything in Google about this error.
I'm using Python 3.3.
I've downloaded Mako-0.7.3 as tar.gz file and just unzipped it in
C:\py\poject\vendor\template\Mako_73. I do not have this directory in the PYTHONPATH or paths.pth. C:\py\poject is a directory where my Django project lives and in \vendor\template I've decided to put Mako and import it from there.
UPD
I found the solution. I've installed the Pyramid Framework and have taken the Mako from there as the Mako is a default template system in it. And Pyramid's version works fine.
Your basic problem is that you are using Python 3, which is relatively new for large projects like Django.
Secondly, you need to find out how to install packages correctly. I don't know where you got Mako from, but you won't find anywhere that says "just unpack the tarball" - perhaps you are assuming that from your knowledge of PHP, but it's not correct.
On the Mako site, the suggested method of installation is pip.
If you go for downloading manually, you need to read instructions about installing Python packages, for example here: http://wiki.python.org/moin/CheeseShopTutorial
The reason Mako doesn't work for you is that the installation procedure (which you haven't run) converts all the provided Python 2 code so that it works on Python 3. It is not that someone didn't bother to check the code for basic syntax errors!
If you are trying to use Django, though, Python 3 is definitely the wrong choice - the installation instructions clearly say you need to be using Python 2.5 to 2.7: https://docs.djangoproject.com/en/1.4/intro/install/
Since you are new to Python, you should try to walk before you run, and go with the tried and tested path - which is Python 2.7 for Django. Ignoring installation instructions and requirements will only slow you down and make life hard.

Building executables for Python 3 and PyQt

I built a rather simple application in Python 3.1 using PyQt4. Being done, I want the application to be distributed to computers without either of those installed.
I almost exclusively care about Windows platforms, so my goal is to have a single executable file and maybe some resource files and .dlls in the end.
Having searched around, I came to the conclusion that
py2exe only supports Python up to version 2.7
pyinstaller only supports Python up to version 2.6
cx_Freeze does not work for me because I keep on getting the following error when trying to execute my successfully build binary:
Y:\Users\lulz\build\exe.win32-3.1>system_shutdown.exe
Traceback (most recent call last):
File "Y:\Program Files (x86)\Python\lib\site-packages\cx_Freeze\initscripts\Console3.py", line 27, in exec(code, m.__dict__)
File "Y:/Users/lulz/Documents/Coding/Python3/projects/System Shutdown/system_shutdown.pyw", line 5, in from PyQt4 import QtCore
File "ExtensionLoader_PyQt4_QtCore.py", line 16, in AttributeError: 'NoneType' object has no attribute 'modules'
So my problem is basically two problems here:
Is there another way but cx_Freeze to build binaries with my configuration?
If not, what might the cx_Freeze problem be?
I can provide more information on the second problem if necessary, like my call of cx_Freeze, my distutils setup script etc.
Thank you already for your help and comments.
You can fix this by appending one line of code to freeze.py in your cx_Freeze package.
It is described here:
http://www.mail-archive.com/cx-freeze-users#lists.sourceforge.net/msg00212.html
It worked for me at least :)
Cheers,
Almar
For Python 3.3 and later, there's a good resolution here:
py2exe - generate single executable file
Install py2exe:
pip install py2exe
Then add besides 'your_script.py' file, the following 'Make_exe.py' file:
from distutils.core import setup
import py2exe, sys
class Make_exe():
def __init__(self, python_script):
sys.argv.append('py2exe')
setup(
console=[{'script': python_script}],
zipfile = None,
options={
'py2exe':
{
'bundle_files': 1,
'compressed': True,
# Add includes if necessary, e.g.
'includes': ['lxml.etree', 'lxml._elementpath', 'gzip'],
}
}
)
if __name__ == '__main__':
Make_exe('your_script.py')
And if you want to make 'your_script.py' rebuild itself as 'your_script.exe' each time you run it in python, you can add to its main:
import subprocess
import sys
if __name__ == '__main__':
currentFile = sys.argv[0]
if currentFile.lower().endswith(".py"):
exitCode = subprocess.call("python Make_exe.py")
if exitCode==0 :
dirName = os.path.dirname(currentFile)
exeName = os.path.splitext(os.path.basename(currentFile))[0] + '.exe'
exePath = dirName + "/dist/" + exeName
cmd = [exePath] + sys.argv[1:]
print ("Executing command:\n %s" % cmd)
exitCode = subprocess.call(cmd)
sys.exit(exitCode)
else:
print ("This will be executed only within the new generated EXE File...")

Resources