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

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.

Related

How do tell "swig -python -py3 myswig.i" not to include annotations

I need to use SWIG to support both Python 2.7 and Python 3.10. [Yes, I know that Python 2.7 is dead, and we're doing our best to migrate users away from it as quickly as we can.]
I generate my module via setuptools.setup with a Swig extension. I can run the setup using both Python2 and Python3. The setuptools program creates a separate shareable library for the Python2 and Python3 runs. However both runs generate a myswig.py file in the same location.
It turns out that the Py2 and Py3 generated files are identical, except that the Py3 generated file contains annotations for the functions and the Py2 doesn't. Python3 can read the Python2 generated file and works just fine. Python2 cannot read the Python3 generated file.
I've tried both %feature("autodoc", 0); and leaving out this line completely, and I still get annotations.
So is there someway of either:
Turning off annotations in the generated file
Adding from __future__ import annotations automatically to the generated file
Don't use -py3. It's not required for Python 3, but enables Python 3-specific code features like annotations.

Using a python library (Biopython) from a python program on a different folder that is installed

I generally like to make my python programs in a text editor and then run them after they are complete instead of line arguments. Thus, I save those .py files on a convenient folder location instead of Python program files.
I then run my .py file using Command Prompt. However it has not worked for the Biopython library as import Bio gives back a Traceback No module named 'Bio'. However, using line arguments directly on python shows it is installed.
I have never had this issue with Python in general and other downloaded libraries (import numpy for example works fine). How do I make the files available to be open from any location?? Or how do I provide the path in import?
To clarify and add:
1) I use Python from Windows 10
2) I downloaded and installed Python(3.7) from python.com
3) I downloaded Biopython using pip (and all other libraries I downloaded)
4) I also tried it on Jupyter notebook and also does not work to import Bio, whereas Import numpy does.
Thanks!

ImportError: DLL load failed: The specified module could not be found -- IBM DB2

I know there have been many people with this same issue, but here is my situation which I have not been able to find the exact same problem. I am building an executable with pyinstaller and I keep getting the importError. I am using ibm_db package to connect to a IBM DB2 database and do inserts into a table using pandas to_sql method. I used pyinstaller on my program before I added the SQL code so I'm pretty sure it has something to do with my trying to connect to DB2, but for the life of me I cannot figure this out.
I get lots of warnings and info messages when I"m running pyinstaller but no errors that I see. I only get the error once I try to execute the executable file that pyinstaller built.
I have tried to run it in a virtual environment to try to isolate the issue but I am not that familiar with virtual environments, so I stop trying to use that.
Traceback (most recent call last):
File "rebate_gui_sql.py", line 9, in <module>
File "c:\users\dt24358\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
exec(bytecode, module.__dict__)
File "site-packages\ibm_db.py", line 10, in <module>
File "site-packages\ibm_db.py", line 9, in __bootstrap__
File "imp.py", line 342, in load_dynamic
ImportError: DLL load failed: The specified module could not be found.
[11020] Failed to execute script rebate_gui_sql
Update: 5/1/2019 from comment below, here is my simple program
import pandas as pd
from tkinter import *
from tkinter import ttk
import ibm_db
import ibm_db_dbi as db
from sqlalchemy import create_engine
class Application(Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master)
self.master = master
self.run_process()
def run_process(self):
engine = create_engine("db2+ibm_db://userid:password#url:port/database")
conn = engine.connect()
print("Connected to " + str(engine))
sql = '''
Select *
from rebteam.pd5
fetch first row only
'''
df = pd.read_sql(sql, conn)
print(df)
df.to_csv(r'c:\users\dt24358\scripts\pricing tool\GUI_SQL\test.csv', index=False)
self.result_label = Label(root, text="Select of PD5 Successful", bg="light green", width=80, justify=LEFT)
self.result_label.grid(row=0,columnspan=2)
root=Tk()
root.title("Rebate Bid Data Upload")
root.configure(background="light green")
app = Application(root)
root.mainloop()
This answer is relevant for these versions:
python - up to 3.7 (but not higher)
pyinstaller 3.4
setuptools 41.0.1
ibm_db 3.0.1
ibm_db_sa 0.3.4
sqlalchemy 1.3.3
There are separate issues here.
The immediate issue (the ImportError) is the failure to load ibm_db.dll
The ImportError happens because pyinstaller does not copy external (non python) libraries into the bundle unless you explicitly request that to happen.
pyinstaller will also not copy a Db2-client into the bundle unless you explicitly tell it to do that, which means that if your target hostname to which you deploy your built-executable does not already have a preconfigured preinstalled Db2-client then you will also experience the failure to load ibm_db module.
The pyinstaller option --add-binary gives a workaround for some kinds of ImportError , see example below. If you are not using SQLAlchemy just skip those parts of this answer.
The pyinstaller option --add-data gives a workaround for adding directories (for example the clidriver directory for adding a Db2-driver) when your target environment lacks a Db2-driver.
Note that this answer does not require you to use SQLAlchemy, the answer is also relevant if you are only using ibm_db (or ibm_db_dbi), in which case just skip the SQLAlchemy parts.
If your python script uses SQLAlchemy to access Db2, then you may see a second symptom at run time after building with pyinstaller. The run time symptom is either:
"sqlalchemy.exc.NoSuchModuleError: Can't load plugin:
sqlalchemy.dialects:ibm_db_sa"
or
"sqlalchemy.exc.NoSuchModuleError: Can't load plugin:
sqlalchemy.dialects:db2.ibm_db"
(depending on the prefix for the url given to create_engine())
This symptom sqlalchemy.exe.NoSuchModuleError is not specific to Db2 but can impact other databases when used via SQLAlchemy with an external dialect ( Db2, teradata, snowflake, presto,...). Databases that use SQLAlchemy internal dialects may just work out of the box.
Here is one workaround for SQLAlchemy, other workarounds are possible.
SQLAlchemy external dialects use pkg_resources entry_points to allow SQLAlchemy to exploit them, but pyinstaller cannot yet handle these, without some assistance from you. Such entry point information is a kind of meta data about the module.
This workaround uses pyinstaller hooks to collect the metadata of the relevant modules , and tells pyinstaller the directory (or directories) that contain these hook files. For Db2 with SQLAlchemy, three hook files are needed, hook-ibm_db.py, hook-ibm_db_sa.py, hook-sqlalchemy.py. I choose to put these hook files in the same directory as my source file python script.
The contents of each of these files is trivial two lines, and the contents differ only by the module name contained within. Here is an example of one of the files hook-sqlalchemy.py (for the other 2 required files, just replace the module name appropriately):
from PyInstaller.utils.hooks import copy_metadata
datas = copy_metadata('sqlalchemy')
To add ibm_db.dll via the --add-binary method, you can either use a command line option to pyinstaller or edit the spec file.
For handling load failures of ibm_db.dll alone, just use the --add-binary additional option like this:
pyinstaller -y --add-binary %LOCALAPPDATA%\Programs\Python\Python37\Lib\site-packages\ibm_db_dlls\ibm_db.dll;.\ibm_db_dlls your_script.py
If you want to include clidriver in your bundle, first find the fully qualified pathname to its location via:
pip show ibm_db
and in the output of that command see the Location: line which has the first part of the fully qualified pathname , so you append \CLIDRIVER to that path and use it in the --add-data additional option like this:
--add-data="c:\path\to\clidriver;.\clidriver"
If you do include clidriver in your bundle, there are additional considerations, see the notes section below.
For apps that also use SQLAlchemy, you need additional steps.
Suppose that the ibm_db.dll lives in this directory:
%LOCALAPPDATA%\programs\python\python37\lib\site-packages\ibm_db_dlls
and you make a variable in a CMD.EXE shell to point to that location:
> set ibm_db_path=%LOCALAPPDATA%\programs\python\python37\lib\site-packages\ibm_db_dlls
For an MS-Windows batch file (using ^ as line continuation character), the pyinstaller command line example to handle both of the workarounds mentioned above is:
pyinstaller -y ^
--additional-hooks-dir=. ^
--hidden-import ibm_db_sa.ibm_db ^
--hidden-import ibm_db_dbi ^
--hidden-import ibm_db ^
--add-binary %LOCALAPPDATA%\Programs\Python\Python37\Lib\site-packages\ibm_db_dlls\ibm_db.dll;.\ibm_db_dlls ^
your_script.py
Notes:
If your python script explicitly imports the SQLAlchemy modules then you do not
need to specify them via --hidden-import options (buy you still need
the hooks for SQLAlchemy to operate after bundling).
For ibm_db versions up to 3.0.2, the ibm_db.dll needs to be in subdirectory ibm_db_dlls in your
bundle, which is the reason for specifying that destination on the
--add-binary option.
If you are building for Linux/Unix, instead of ^. use \ as the line continuation character as usual.
If you intend to copy your built executable to a new hostname, and that new hostname does not already have a pre-installed Db2-client , and you do not wish to install a separate Db2-client on the target, then you can bundle clidriver with the pyinstaller output with the --add-data option shown above.
If you bundle clidriver be aware that you may also need to bundle its configuration files (such as db2dsdriver.cfg and db2cli.ini) if they are in non-default locations, depending on whether your code uses externally configured DSNs or long connection-strings. If you do not bundle such configuration files (implicitly or explicitly) and you deploy your built environment to a different hostname than the build environment then you will need to reconfigure those files at the target hostname. The default location for these files is in the clidriver\cfg directory which will get included via --add-data as mentioned earlier.
If you bundle clidriver, and if you are using encrypted connections to Db2 via TLS/SSL, be aware you may also need to bundle additional files such as certificates, keystore/stash files etc when you run the pyinstaller build.
If you bundle clidriver, be aware that IBM refreshes this component a couple of times per year with bug fixes and security fixes and new functions, so you may need to refresh your executables periodically to prevent them from becoming security holes by being frozen in time with old versions.
if you bundle clidriver and if you need to use odbcad32 on the target hostname for configuring Db2 DSNs, then following deployment on the target hostname remember to run the clidriver\bin\db2cli install -setup command on the target hostname.
Thanks for your question and answer. I had met the same situation in Windows7 Python3.7 ibm-db 3.0.1
with your hint,I think the reason is that exe can't find *.dll in clidriver\bin and ibm_db.dll,
and solve it with a similar method in two steps
Frist:
the same as you, add clidriver directory to system path
**\site-packages\clidriver\bin
Second
pack with argument --add-binary
Pyinstaller --add-binary **\Lib\site-packages\ibm_db_dlls\ibm_db.dll;.\ibm_db_dlls myproject.py
Then it's OK!
similar question:
PyQt5 Executable is crashing with Missing DLL

Issue with python import for mapr_streams_python

I'm playing with the MapR Sandbox and would like to import some data in MapR stream using python. But I'm having an importing issue and I dont know why. I followed instructions from MApR website (see reference at the end of this post) and looked everywhere for a clue, but know I don't really know what else I can do. I tried with python 2.7 and python 3.6.
File "producer.py", line 1, in <module>
from mapr_streams_python import Producer
ModuleNotFoundError: No module named 'mapr_streams_python'
I have installed it globally like doc is telling me to do, the file is located in /usr/lib64/python2.7/site-packages for python 2 /usr/lib64/python3.6/site-packages for python 3
Someone has an idea?
Thank you
References
https://mapr.com/docs/60/AdvancedInstallation/InstallingStreamsPYClient.html
https://mapr.com/docs/52/MapR_Streams/MapRStreamsPythonExample.html
I noticed that the folder for the module was incorrectly named in the folder that it was installed at. After getting to the directory with the modules (/usr/lib64/python3.6/site-packages), just run this command:
cp -R mapr_streams_python-0.11.0-py3.6.egg-info/ mapr_streams_python
You should then be able to import the package in python.

python3 importing pygame results in PyCObject_AsVoidPtr

I have encountered difficulty putting pygame together with python3 on my MacBookPro.
I installed Python 3.3, and my MacOS is running version 10.7.5.
Then I downloaded pygamev1.9.1 source code, and followed instructions in http://programming.itcarlow.ie/PyGameInstall.pdf
Compilation and installation was smooth until I issued "import pygame" inside python3.
Then I encountered the following "PyCobJect_AsVoidPtr" error (further text following error message):
import pygame
Traceback (most recent call last):
File "", line 1, in
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pygame/init.py", line 95, in
from pygame.base import *
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pygame/base.so, 2): Symbol not found: _PyCObject_AsVoidPtr
Referenced from: /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pygame/base.so
Expected in: flat namespace
in /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pygame/base.so
A search on google indicates this symbol has been removed since Python3.2:
http://mail.python.org/pipermail/python-dev/2011-March/108882.html
Can someone please give me some advice on how to get pygame working on Python3.3?
More so, whereas I am aware the pygame/python3 developers are busy with their work, but I would certainly appreciate it if someone can provide precompiled pygame binaries for python3. I have limited computer skills, and I just want to go ahead and learn Python3 and pygame, and this is seriously stunting my interest.
I notice that you were trying to compile from source, but builds on Python 3.3, to my knowledge, are not yet supported (as of January 2013). In fact, the only binaries I'm aware of for PyGame and Python 3.3 are unofficial builds and Windows only.
You should consider instead using a previous version of Python (e.g. Python 2.7.*), PyGame builds/binaries on which are well-supported. Any points on setting up should be directed to the pygame-users mailing list, if they weren't already.

Resources