PyInstaller & Pymeasure : NotImplementedError - python

I am currently experiencing difficulties using PyInstaller on a code relying on Pymeasure library. The program is working fine from the prompt, but not when started from the executable generated by PyInstaller.
Here is an simple example of a code working from prompt but not when frozen:
import visa
from pymeasure.instruments.keithley import Keithley2000, Keithley2400
rm = visa.ResourceManager()
list_available = rm.list_resources()
print(list_available)
keithley = Keithley2400("GPIB1::23")
keithley.apply_current() # Sets up to source current
keithley.source_current_range = 10e-3 # Sets the source current range to 10 mA
keithley.compliance_voltage = 10 # Sets the compliance voltage to 10 V
keithley.source_current = 0 # Sets the source current to 0 mA
keithley.enable_source() # Enables the source output
keithley.measure_voltage() # Sets up to measure voltage
keithley.ramp_to_current(5e-3) # Ramps the current to 5 mA
print(keithley.voltage) # Prints the voltage in Volts
keithley.shutdown() # Ramps the current to 0 mA and disables output
Here is the output when I run the executable:
Please note that I have PyVISA 1.9.1 installed.
Why do I get this error and how do I fix that ?

You need to make sure you include the package metadata for PyVisa in your PyInstaller project. PyInstaller has a utility hook for that job; create a hook-pyvista.py hook file (if you don’t already have one) with:
from PyInstaller.utils.hooks import copy_metadata
datas = copy_metadata("pyvisa")
and tell PyInstaller about it with the --additional-hooks-dir command-line switch. See the documentation on how hooks work for more details.
pymeasurement relies on the pyvisa.__version__ attribute to determine if you have installed the correct version of that project. But pyvisa.__version__ defaults to "unknown" unless it can locate its metadata files, which would provide pkg_resources with the required metadata to retrieve the version for it.
You can verify that PyVisa was installed correctly by importing it yourself and testing the __version__ attribute:
import pyvisa
print("PyVisa version", pyvisa.__version__)

Are you sure you are connected to the instrument, your code references "GPIB1::23" but your print(list_available) returns "GPIB1::24"?

Related

Unable to select a box in a python script when launching Blender from console

For my project, I want to be able to run a Blender python script from the system console.
This minimal script (see below) is able to select a region, using the select_box operator. The script works correctly when launching from the blender application. However, when running it from the console, using "C:\Program Files\Blender Foundation\Blender 2.81\blender.exe" "C:\Users\Desktop\test.blend" -d --python "D:\Documents\minTest.py", the program crash with the following output:
Switching to fully guarded memory allocator.
Blender 2.81 (sub 16)
Build: 2019-12-04 14:30:40 Windows Release
argv[0] = C:\Program Files\Blender Foundation\Blender 2.81\blender.exe
argv[1] = C:\Users\Desktop\test.blend
argv[2] = -d
argv[3] = --python
argv[4] = D:\Documents\minTest.py
Read prefs: C:\Users\AppData\Roaming\Blender Foundation\Blender\2.81\config\userpref.blend
read file
Version 280 sub 39 date unknown hash unknown
found bundled python: C:\Program Files\Blender Foundation\Blender 2.81\2.81\python
Warning: Add-on 'io_mesh_xyz' was not upgraded for 2.80, ignoring
Warning: Add-on 't26_PointCloudSkinner1_Umbrella' was not upgraded for 2.80, ignoring
Read blend: C:\Users\Desktop\test.blend
read file C:\Users\Desktop\test.blend
Version 281 sub 16 date 2019-12-04 11:32 hash f1aa4d18d49d
***** DEBUG: working
Error : EXCEPTION_ACCESS_VIOLATION
Address : 0x00007FF60F40DCFD
Module : C:\Program Files\Blender Foundation\Blender 2.81\blender.exe
The test.blend file is the simple startup scene. The minTest.py script is the following:
import bpy
def getView3dAreaAndRegion():
for area in bpy.context.screen.areas:
if area.type == "VIEW_3D":
for region in area.regions:
if region.type == "WINDOW":
return area, region
view3dArea, view3dRegion = getView3dAreaAndRegion()
override = bpy.context.copy()
override['area'] = view3dArea
override['region'] = view3dRegion
print("***** DEBUG: working") #Debug to see that the script has launched
bpy.ops.view3d.select_box(override,xmin=100, xmax=500, ymin=100, ymax=300, wait_for_input=False)
More information:
I'm using Blender 2.81 and Python 3.7 (bundled in Blender).
The script works just fine if I remove the call to select_box in both Blender and from console.
So my questions are:
Why do I have different result according to how I launch the script?
What should I do to be able to run the script from the system console?
You can't expect consistent results if you want to imitate user input with a script, it is too hard to know where anything is positioned.
To get reliable results from a script, you need to work with consistent data, so compare the objects location to decide if it is within certain criteria.
import bpy
for obj in bpy.context.scene.objects:
if obj.location.z > 0.2 and obj.location.z < 1.5:
obj.select_set(True)
else:
obj.select_set(False)
If you want to select a portion of a mesh, decide on what is selected either based on its position relative to the object origin or its world position by using obj.matrix_world.
While you can directly access the mesh components in obj.data, you should consider using bmesh for any mesh editing.
import bpy
import bmesh
bpy.ops.object.mode_set(mode='EDIT')
me = bpy.context.object.data
bm = bmesh.from_edit_mesh(me)
for v in bm.verts:
if v.co.z > -1.8 and v.co.z < 0.5:
v.co.z += 0.2
v.select = True
else:
v.select = False
bmesh.update_edit_mesh(me)
bm.free()
bpy.ops.object.mode_set(mode='OBJECT')
For help with blender specific scripting ask at blender.stackexchange.

How to load the Odoo Environment into a Jupyter Notebook?

Odoo (ERP)
Odoo is an all-in-one management software that offers a range of business applications that form a complete suite of enterprise management applications targeting companies of all sizes. Odoo is an all-in-one business software including CRM, website/e-commerce, billing, accounting, manufacturing, warehouse - and project management, and inventory.
The Community version is the open source version while the Enterprise version supplements the Community edition with commercial features and services.
Terminal
Usually I launch a Python Terminal with the Odoo environment loaded like this:
/odoo_path/odoo-bin --addons-path=/addons_path shell --config=/config_path/.odoo.conf -d database_name
Inside the console I can call to self, and the environment variable is available (self.env). And I can run some commands over the connected database. If I want to do some fast tests this is very useful. But it is kind of inconvinient if I want to run some small scripts or test some code snippets. Jupyter Notebooks and Jupyter Lab are very good tools for that.
Jupyter
Jupyter is a project which produces browser-based interactive environments for programming, mathematics, and data science. It supports a number of languages via plugins ("kernels"), such as Python, Ruby, Haskell, R, Scala and Julia.
Jupyter Notebook is the traditional and most stable application. JupyterLab has a new interface and is more suitable for working with larger projects consisting of multiple files. JupyterLab is in beta as of February 2018.
(source: windows.net)
Requests
What I want to achieve is load the Odoo environment into a Jupyter Notebook and work with these code snippets instead of the simple Python Terminal.
So I am wondering if anyone knows if this is doable or which would be a good place to start. Is there a better alternative? Is this a silly idea?
Step 1. install jupyter in your odoo environment
pip install jupyter
Step 2.
Start odoo shell and open jupyter from the python prompt
>>
from notebook.notebookapp import NotebookApp
import tornado.ioloop
app = NotebookApp()
app.initialize(["--ip=0.0.0.0"])
tornado.ioloop.IOLoop.current().start()
Step 3.
Get the token by sending CTRL+C to the python console
You see something like
http://(<hostname> or 127.0.0.1):8888/?token=9d150bd69e908df9a5e30157b530624536fe0c84d8804f17
Step 4.
Open your browser
http://localhost:8888/?token=9d150bd69e908df9a5e30157b530624536fe0c84d8804f17
Now you are in the Jupyter console or web interface
To connect to odoo you need to set the system path and then connect
import sys
sys.path[0:0] = [
'/vagrant/odoo/py3o.template',
'/vagrant/odoo/openupgradelib',
'/vagrant/odoo/anybox.recipe.odoo',
'/vagrant/odoo/pyusb',
'/vagrant/odoo/parts/odoo',
'/vagrant/odoo/eggs/gevent-1.1.2-py2.7-linux-x86_64.egg',
'/vagrant/odoo/eggs/Unidecode-1.1.1-py2.7.egg',
'/vagrant/odoo/eggs/py3o.formats-0.3-py2.7.egg',
'/vagrant/odoo/eggs/isoweek-1.3.3-py2.7.egg',
'/vagrant/odoo/eggs/PyPDF2-1.26.0-py2.7.egg',
'/vagrant/odoo/eggs/simplejson-3.17.2-py2.7-linux-x86_64.egg',
'/vagrant/odoo/eggs/xlrd-1.2.0-py2.7.egg',
'/vagrant/odoo/eggs/openpyxl-2.4.9-py2.7.egg',
'/vagrant/odoo/eggs/vcrpy-3.0.0-py2.7.egg',
'/vagrant/odoo/eggs/py2_ipaddress-3.4.2-py2.7.egg',
'/vagrant/odoo/eggs/Babel-2.8.0-py2.7.egg',
'/vagrant/odoo/eggs/decorator-4.4.2-py2.7.egg',
'/vagrant/odoo/eggs/docutils-0.16-py2.7.egg',
'/vagrant/odoo/eggs/feedparser-5.2.1-py2.7.egg',
'/vagrant/odoo/eggs/Jinja2-2.10.1-py2.7.egg',
'/vagrant/odoo/eggs/lxml-4.5.2-py2.7-linux-x86_64.egg',
'/vagrant/odoo/eggs/Mako-1.1.3-py2.7.egg',
'/vagrant/odoo/eggs/mock-2.0.0-py2.7.egg',
'/vagrant/odoo/eggs/ofxparse-0.20-py2.7.egg',
'/vagrant/odoo/eggs/passlib-1.7.4-py2.7.egg',
'/vagrant/odoo/eggs/Pillow-4.1.1-py2.7-linux-x86_64.egg',
'/vagrant/odoo/eggs/psutil-2.2.1-py2.7-linux-x86_64.egg',
'/vagrant/odoo/eggs/psycogreen-1.0.2-py2.7.egg',
'/vagrant/odoo/eggs/psycopg2-2.8.6-py2.7-linux-x86_64.egg',
'/vagrant/odoo/eggs/Python_Chart-1.39-py2.7.egg',
'/vagrant/odoo/eggs/pydot-1.4.1-py2.7.egg',
'/vagrant/odoo/eggs/pyparsing-2.4.7-py2.7.egg',
'/vagrant/odoo/eggs/pyPdf-1.13-py2.7.egg',
'/vagrant/odoo/eggs/pyserial-3.4-py2.7.egg',
'/vagrant/odoo/eggs/python_dateutil-2.8.1-py2.7.egg',
'/vagrant/odoo/eggs/python_ldap-3.3.1-py2.7-linux-x86_64.egg',
'/vagrant/odoo/eggs/python_openid-2.2.5-py2.7.egg',
'/vagrant/odoo/eggs/pytz-2020.1-py2.7.egg',
'/vagrant/odoo/eggs/PyYAML-5.3.1-py2.7-linux-x86_64.egg',
'/vagrant/odoo/eggs/qrcode-6.1-py2.7.egg',
'/vagrant/odoo/eggs/reportlab-2.7-py2.7-linux-x86_64.egg',
'/vagrant/odoo/eggs/requests-2.24.0-py2.7.egg',
'/vagrant/odoo/eggs/suds_jurko-0.6-py2.7.egg',
'/vagrant/odoo/eggs/vatnumber-1.2-py2.7.egg',
'/vagrant/odoo/eggs/vobject-0.9.6.1-py2.7.egg',
'/vagrant/odoo/eggs/Werkzeug-0.11.11-py2.7.egg',
'/vagrant/odoo/eggs/XlsxWriter-1.3.6-py2.7.egg',
'/vagrant/odoo/eggs/xlwt-1.3.0-py2.7.egg',
'/vagrant/odoo/eggs/python_stdnum-1.14-py2.7.egg',
'/vagrant/odoo/eggs/urllib3-1.25.10-py2.7.egg',
'/vagrant/odoo/eggs/idna-2.10-py2.7.egg',
'/vagrant/odoo/eggs/chardet-3.0.4-py2.7.egg',
'/vagrant/odoo/eggs/certifi-2020.6.20-py2.7.egg',
'/vagrant/odoo/eggs/six-1.15.0-py2.7.egg',
'/vagrant/odoo/eggs/pyasn1_modules-0.2.8-py2.7.egg',
'/vagrant/odoo/eggs/pyasn1-0.4.8-py2.7.egg',
'/vagrant/odoo/eggs/olefile-0.46-py2.7.egg',
'/vagrant/odoo/eggs/beautifulsoup4-4.9.3-py2.7.egg',
'/vagrant/odoo/eggs/pbr-5.5.0-py2.7.egg',
'/vagrant/odoo/eggs/funcsigs-1.0.2-py2.7.egg',
'/vagrant/odoo/eggs/MarkupSafe-1.1.1-py2.7-linux-x86_64.egg',
'/vagrant/odoo/eggs/greenlet-0.4.17-py2.7-linux-x86_64.egg',
'/vagrant/odoo/eggs/zc.recipe.egg-2.0.7-py2.7.egg',
'/vagrant/odoo/eggs/wrapt-1.12.1-py2.7-linux-x86_64.egg',
'/vagrant/odoo/eggs/contextlib2-0.6.0.post1-py2.7.egg',
'/vagrant/odoo/eggs/et_xmlfile-1.0.1-py2.7.egg',
'/vagrant/odoo/eggs/jdcal-1.4.1-py2.7.egg',
'/vagrant/odoo/eggs/pyjon.utils-0.7-py2.7.egg',
'/vagrant/odoo/eggs/Genshi-0.7.3-py2.7-linux-x86_64.egg',
'/vagrant/odoo/eggs/cssselect-1.1.0-py2.7.egg',
'/vagrant/odoo/eggs/soupsieve-1.9.5-py2.7.egg',
'/vagrant/odoo/eggs/backports.functools_lru_cache-1.6.1-py2.7.egg',
'/home/vagrant/venv/lib/python2.7/site-packages',
]
from anybox.recipe.odoo.runtime.session import Session
%%capture
session = Session('/vagrant/odoo/etc/odoo.cfg', '/vagrant/odoo')
%%capture
session.open(db='odootest')
User = session.env['res.users']
user = User.browse(1)
print(user.name)
Administrator
Please find attached a minimal odoo buildout script
[buildout]
parts = odoo
versions = versions
# Mr Developer Extension
extensions = mr.developer
auto-checkout = *
always-checkout = force
[sources]
# Sources that Mr Developer needs to check out
anybox.recipe.odoo = git https://github.com/anybox/anybox.recipe.odoo branch=master
openupgradelib = git https://github.com/OCA/openupgradelib branch=master
odoocrpc = git https://github.com/OCA/odoorpc branch=master
[odoo]
release = 14.0
apply-requirements-file = True
recipe = anybox.recipe.odoo:server
eggs =
gevent
odoorpc
openupgradelib
unidecode
inouk.recipe.odoo_cmd
odoo_scripts =
command-line-options=-d
odoo_cmd=odoo-bin
version = git https://github.com/odoo/odoo.git odoo ${odoo:release}
# This directive will nuke local changes, but without it, a branch with merges
# cannot be updated if the main branch has progressed. This will break
# rebuilds. Use this in production and testing, not in development.
vcs-clear-retry = True
git-warn-sha-pins = False
addons =
git https://github.com/oca/web parts/web ${odoo:release}
git https://github.com/oca/server-tools parts/server-tools ${odoo:release}
merges =
# Config options
options.http_enable = True
options.http_port = 8169
options.lang = nl_NL
options.limit_time_cpu = 36000
options.limit_time_real = 72000
options.log_handler = :DEBUG,werkzeug:CRITICAL,openerp.service.server:INFO,PIL:INFO
options.log_level = debug
options.logrotate = True
options.longpolling_port = 8170
# options.proxy_mode = True
# options.without_demo = False
options.workers = 4
[versions]
xlwt = 1.3.0

Where is model directory in pocketsphinx

I'm trying to make a simple speech recognition program in Python using Sphinx. I installed it using pip in CMD, then I installed PocketSphinx in the same way. The tutorial I'm following says I need to include the model directories for PocketSphinx, but I don't know where the directory is. How do I find it, and am I doing something wrong?
If you are using pocketsphinx-python installed via pip, and following some example code similar to that provided by the package's github page, you may find there are a few code changes needed.
Here's what's currently in the README (as of March 11, 2018):
from pocketsphinx.pocketsphinx import *
from sphinxbase.sphinxbase import *
MODELDIR = "pocketsphinx/model"
DATADIR = "pocketsphinx/test/data"
# Create a decoder with certain model
config = Decoder.default_config()
config.set_string('-hmm', path.join(MODELDIR, 'en-us/en-us'))
config.set_string('-lm', path.join(MODELDIR, 'en-us/en-us.lm.bin'))
config.set_string('-dict', path.join(MODELDIR, 'en-us/cmudict-en-us.dict'))
This not-yet-accepted pull request describes some changes which may help for those of us using pip and working on our python code outside the downloaded module's directory (at least in a *nix/Mac environment, I haven't tested on Windows). Here's a diff snippet; the key idea is to use path.dirname(pocketsphinx.__file__) to get the base directory in which to look for the model directory:
-MODELDIR = "pocketsphinx/model"
-DATADIR = "pocketsphinx/test/data"
+import pocketsphinx;
+POCKETSPHINXDIR = path.dirname(pocketsphinx.__file__)
+MODELDIR = path.join(POCKETSPHINXDIR, "model")
+DATADIR = path.join(POCKETSPHINXDIR, "data")
(Small note: I took liberty to fix a small typo in the spelling of POCKETSPHINXDIR, so this code isn't exactly the same as the pull request)
Go the location where your python is installed look for the following location inside that (this location is according to windows installation)
Lib\site-packages\speech_recognition\pocketsphinx-data
default model is en-US however there are few other language models that one can download from here
https://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/
It may be late to answer now, but for newcomers, Python module has some convenience methods:
from pocketsphinx import get_model_path, get_data_path
print(get_model_path())
print(get_data_path())

How does one set specific vim-bindings in Ipython 5.0.0

I understand that because Ipython 5.0.0 uses a new input library (prompt_toolkit) it no longer defaults to the editor mode specified in .inputrc (*nix). This option has to be set in an Ipython profile configuration file (see https://stackoverflow.com/a/38329940/2915339).
My question is: having set vi-mode in the profile configuration file, how does one specify a particular keybinding? I like to use 'jk' for escape, for instance.
You're right. prompt_toolkit ignores .inputrc. There does not seem to be a way to define custom keybindings for the vi mode in the IPython 5.0.0 profile configuration file.
Here's workaround I'm currently using. It's not pretty, but it works for now.
According to the IPython docs, you can specify Keyboard Shortcuts in a startup configuration script.
Instead of rebinding jk to ESC, I'm making a unicode "j" (u'j') followed by a unicode "k" (u'k') inside of VimInsertMode() a shortcut for a prompt_toolkit event that switches to navigation mode.
I created a .ipython/profile_default/startup/keybindings.py with the following code:
from IPython import get_ipython
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import HasFocus, ViInsertMode
from prompt_toolkit.key_binding.vi_state import InputMode
ip = get_ipython()
def switch_to_navigation_mode(event):
vi_state = event.cli.vi_state
vi_state.reset(InputMode.NAVIGATION)
if getattr(ip, 'pt_cli'):
registry = ip.pt_cli.application.key_bindings_registry
registry.add_binding(u'j',u'k',
filter=(HasFocus(DEFAULT_BUFFER)
& ViInsertMode()))(switch_to_navigation_mode)
The prompt_toolkit source will help you implement other shortcuts as needed.
This is an old post but it helped me find my answer so I thought I would post how I added a couple of bindings to vi mode in ipython. I added the following code in ~/.ipython/profile_default/startup/00-keybindings.py to bind to K and J in vi navigation mode.
"""Improve history access so I can skip over functions"""
from IPython import get_ipython
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import HasFocus, ViNavigationMode
from prompt_toolkit.key_binding.bindings.named_commands import get_by_name
ip = get_ipython()
registry = ip.pt_app.key_bindings
ph = get_by_name('previous-history')
nh = get_by_name('next-history')
registry.add_binding('K',
filter=(HasFocus(DEFAULT_BUFFER) &
ViNavigationMode()))(ph)
registry.add_binding('J',
filter=(HasFocus(DEFAULT_BUFFER) &
ViNavigationMode()))(nh)

Python - How to get the start/base address of a process?

How do I get the start/base address of a process? Per example Solitaire.exe (solitaire.exe+BAFA8)
#-*- coding: utf-8 -*-
import ctypes, win32ui, win32process
PROCESS_ALL_ACCESS = 0x1F0FFF
HWND = win32ui.FindWindow(None,u"Solitär").GetSafeHwnd()
PID = win32process.GetWindowThreadProcessId(HWND)[1]
PROCESS = ctypes.windll.kernel32.OpenProcess(PROCESS_ALL_ACCESS,False,PID)
print PID, HWND,PROCESS
I would like to calculate a memory address and for this way I need the base address of solitaire.exe.
Here's a picture of what I mean:
I think the handle returned by GetModuleHandle is actually the base address of the given module. You get the handle of the exe by passing NULL.
Install pydbg
Source: https://github.com/OpenRCE/pydbg
Unofficial binaries here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pydbg
from pydbg import *
from pydbg.defines import *
import struct
dbg = pydbg()
path_exe = "C:\\windows\\system32\\calc.exe"
dbg.load(path_exe, "-u amir")
dbg.debug_event_loop()
parameter_addr = dbg.context.Esp #(+ 0x8)
print 'ESP (address) ',parameter_addr
#attach not working under Win7 for me
#pid = raw_input("Enter PID:")
#print 'PID entered %i'%int(pid)
#dbg.attach(int(pid)) #attaching to running process not working
You might want to have a look at PaiMei, although it's not very active right now https://github.com/OpenRCE/paimei
I couldn't get attach() to work and used load instead. Pydbg has loads of functionality, such as read_proccess_memory, write_process_memory etc.
Note that you can't randomly change memory, because an operating system protects memory of other processes from your process (protected mode). Before the x86 processors there were some which allowed all processors to run in real mode, i.e. the full access of memory for every programm. Non-malicious software usually (always?) doesn't read/write other processes' memory.
The HMDOULE value of GetModuleHandle is the base address of the loaded module and is probably the address you need to compute the offset.
If not, that address is the start of the header of the module (DLL/EXE), which can be displayed with the dumpbin utility that comes with Visual Studio or you can interpret it yourself using the Microsoft PE and COFF Specification to determine the AddressOfEntryPoint and BaseOfCode as offsets from the base address. If the base address of the module isn't what you need, one of these two is another option.
Example:
>>> BaseAddress = win32api.GetModuleHandle(None) + 0xBAFA8
>>> print '{:08X}'.format(BaseAddress)
1D0BAFA8
If The AddressOfEntryPoint or BaseOfCode is needed, you'll have to use ctypes to call ReadProcessMemory following the PE specification to locate the offsets, or just use dumpbin /headers solitaire.exe to learn the offsets.
You can use frida to easy do that.
It is very useful to make hack and do some memory operation just like make address offset, read memory, write something to special memory etc...
https://github.com/frida/frida
2021.08.01 update:
Thanks for #Simas Joneliunas reminding
There some step using frida(windows):
Install frida by pip
pip install frida-tools # CLI tools
pip install frida # Python bindings
Using frida api
session = frida.attach(processName)
script = session.create_script("""yourScript""")
script.load()
sys.stdin.read() #make program always alive
session.detach()
Edit your scrip(using JavaScrip)
var baseAddr = Module.findBaseAddress('solitaire.exe');
var firstPointer = baseAddr.add(0xBAFA8).readPointer();
var secondPointer = firstPointer.add(0x50).readPointer();
var thirdPointer = secondPointer.add(0x14).readPointer();
#if your target pointer points to a Ansi String, you can use #thirdPointer.readAnsiString() to read
The official site https://frida.re/

Categories