How do I get the OS and system modules into py2exe - python-3.x

I am trying to create a stand alone application for a windows computer I am trying to use the following modules:
os
system
threading
time
But it is not allowing me to import any of these modules it doesn't give me an error code or anything it just will not load the modules into the file! from distutils.core import setup
import py2exe
setup(console=['Evil_unlocker_final.py']
options={
"os":{
"unbuffered": True,
"optimize": 2
}
"sys":{
"unbuffered": True,
"optimize": 2
}
}
)

You do not have to add the os library nor do you have to add the system library the error is in the setup.py file it is not formatted correctly all you need in your setup.py file
setup(console=['Evil_unlocker_final.py'])
That's it the only time that you would need to add in the options function is when you are importing a module that is not built into python for example if you wanted to add in the flask and jinja2 libraries your file would have to also have to add options and your file would look somewhat like this
setup(console=['Evil_unlocker_final.py']
options={
"pip":{
"unbuffered": True,
"optimize": 2
}
"jinja2":{
"unbuffered": True,
"optimize": 2
}
}
)

Related

Checking for existing webdriver when using selenium

I am trying to use selenium to control Chrome at work. The methods I have found all seem to install the webdriver every time the code is run. However, because of work from home and a rather slow VPN, this can take upto a minute. So, I am trying to check for the webdriver executable and then skip the install method if it exists.
Issue: When searching the directory, the the files list is empty.
chromedriver.exe does exist in C:\Users<user>.wdm\drivers\chromedriver\win32\103.0.5060 as installed by a previous run.
import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
# set a variable for the web driver folder.
wddir = os.environ["USERPROFILE"] + "\.wdm\drivers\chromedriver\win32"
# check the existance of the folder.
# if it exists, find the driver and set it
if os.path.exists(wddir):
wdname = "chromedriver.exe"
for root, dir, files in os.walk(wddir):
if wdname in files:
driver = webdriver.Chrome(os.path.join(root, wdname))
else: #install the driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
Resulting variable list:
- dir: ['103.0.5060']
- files: []
- root: C:\Users\<user>\.wdm\drivers\chromedriver\win32
- wddir: C:\Users\<user>\.wdm\drivers\chromedriver\win32
- wdname: chromedriver.exe
Since files = [], it goes on to install the driver anyway.
As an aside, is this a viable method for skipping the install? I am open to suggestions for better methods.

Why there is a permisson denied error while using node-tesseract-ocr?

I am using node-tesseract-ocr library for using ocr for my node js project. I installed tesseract-ocr in my machine(windows) using choco and then node-tesseract-ocr using npm. While requesting that particular route I am getting the following error
Error, cannot read input file "myActualPath": Permission denied
Error during processing.
This is the code I am using
const config = {
lang: 'eng',
oem: 1,
psm: 3,
};
tesseract
.recognize(__dirname, `../public/data/${reciept}`, config)
.then((text) => {
serialResponse = text.match(new RegExp(serial, 'g'));
})
.catch((error) => {
console.log(error.message);
});
Make sure you have added the tesseract-OCR path in your environment variables, and restart your IDE
Note, for programs like PyCharm and many others, you need to also close the program and re-open it after setting the system environment variable - As told by silas in another post similar to this one.
You can refer that post here .
Make sure to import the necessary packages in your module
import pytesseract
import argparse
import cv2
Then construct the argument parser and parse the arguments.
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to input image to be OCR'd")
args = vars(ap.parse_args())
Note The first Python import you’ll notice in this script is pytesseract (Python Tesseract), a Python binding that ties in directly with the Tesseract OCR application running on your system. The power of pytesseract is our ability to interface with Tesseract rather than relying on ugly os.cmd calls as we needed to do before pytesseract ever existed.
For additional reference.

Loading python modules in Python 3

How do I load a python module, that is not built in. I'm trying to create a plugin system for a small project im working on. How do I load those "plugins" into python? And, instaed of calling "import module", use a string to reference the module.
Have a look at importlib
Option 1: Import an arbitrary file in an arbiatrary path
Assume there's a module at /path/to/my/custom/module.py containing the following contents:
# /path/to/my/custom/module.py
test_var = 'hello'
def test_func():
print(test_var)
We can import this module using the following code:
import importlib.machinery
myfile = '/path/to/my/custom/module.py'
sfl = importlib.machinery.SourceFileLoader('mymod', myfile)
mymod = sfl.load_module()
The module is imported and assigned to the variable mymod. We can then access the module's contents as:
mymod.test_var
# prints 'hello' to the console
mymod.test_func()
# also prints 'hello' to the console
Option 2: Import a module from a package
Use importlib.import_module
For example, if you want to import settings from a settings.py file in your application root folder, you could use
_settings = importlib.import_module('settings')
The popular task queue package Celery uses this a lot, rather than giving you code examples here, please check out their git repository

EnsureDispatch error when using cx_freeze for making exe

I am working with Python 3.4 on Windows 7. My setup file is as follows:
from cx_Freeze import setup, Executable, sys
exe=Executable(
script="XYZ.py",
base="Win32Gui",
)
includefiles=[]
includes=[]
excludes=[]
packages=[]
setup(
version = "1.0",
description = "XYZ",
author = "MAX",
name = "AT",
options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}},
executables = [exe]
)
from distutils.core import setup
import py2exe, sys, os, difflib
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1}},
console = [{'script': "XYZ.py"}],
zipfile = None,
)
When the obtained exe is run, an error pops up saying:
...
File "C:\Python34\Lib\site-packages\win32com\client\CLSIDToClass.py", line 46, in GetClass
return mapCLSIDToClass[clsid]
KeyError: '{00020970-0000-0000-C000-000000000046}'
I just can't figure out the problem here. Help, please.
Thanks.
I've just figured out that the problem with EnsureDispatch is within gencache module, it assumes to be in read-only mode when an executable is built with cx_freeze.
The following lines allow cache to be built inside AppData\Local\Temp\gen_py\#.#\ directory in Windows 7 x64:
from win32com.client import gencache
if gencache.is_readonly:
gencache.is_readonly = False
gencache.Rebuild() #create gen_py folder if needed
References:
py2exe/pyinstaller and DispatchWithEvents answer
py2exe.org: UsingEnsureDispatch
P. S. Performance is much better with static dispatch
You are using static proxy which is generated on your disk and which has the compiled executable trouble finding. If you do not know what the static proxy is, you are probably using win32com.client.gencache.EnsureDispatch which generates static proxy automatically.
The easiest way to fix the problem is to use dynamic proxy by using win32com.client.dynamic.Dispatch. Static proxy has some benefits, but there is a high possibility that you do not need it.
You can find more information about static and dynamic proxies to COM objects here: http://timgolden.me.uk/python/win32_how_do_i/generate-a-static-com-proxy.html

Py2exe: Embed static files in exe file itself and access them

I found a solution to add files in library.zip via: Extend py2exe to copy files to the zipfile where pkg_resources can load them.
I can access to my file when library.zip is not include the exe.
I add a file : text.txt in directory: foo/media in library.zip.
And I use this code:
import pkg_resources
import zipfile
from cStringIO import StringIO
my_data = pkg_resources.resource_string(__name__,"library.zip")
filezip = StringIO(my_data)
zip = zipfile.ZipFile(filezip)
data = zip.read("foo/media/text.txt")
I try to use pkg_resources but I think that I don't understand something because I could open directly "library.zip".
My question is how can I do this when library.zip is embed in exe?
Best Regards
Jean-Michel
I cobbled together a reasonably neat solution to this, but it doesn't use pkg_resources.
I need to distribute productivity tools as standalone EXEs, that is, all bundled into the one .exe file. I also need to send out notifications when these tools are used, which I do via the Logging API, using file-based configuration. I emded the logging.cfg fileto make it harder to effectively switch-off these notifications i.e. by deleting the loose file... which would probably break the app anyway.
So the following is the interesting bits from my setup.py:
LOGGING_CFG = open('main/resources/logging.cfg').read()
setup(
name='productivity-tool',
...
# py2exe extras
console=[{'script': productivity_tool.__file__.replace('.pyc', '.py'),
'other_resources': [(u'LOGGINGCFG', 1, LOGGING_CFG)]}],
zipfile=None,
options={'py2exe': {'bundle_files': 1, 'dll_excludes': ['w9xpopen.exe']}},
)
Then in the startup code for productivity_tool.py:
from win32api import LoadResource
from StringIO import StringIO
from logging.config import fileConfig
...
if __name__ == '__main__':
if is_exe():
logging_cfg = StringIO(LoadResource(0, u'LOGGINGCFG', 1))
else:
logging_cfg = 'main/resources/logging.cfg'
fileConfig(logging_cfg)
...
Works a treat!!!
Thank you but I found the solution
my_data = pkg_resources.resource_stream("__main__",sys.executable) # get lib.zip file
zip = zipfile.ZipFile(my_data)
data = zip.read("foo/media/doc.pdf") # get my data on lib.zip
file = open(output_name, 'wb')
file.write(data) # write it on a file
file.close()
Best Regards
You shouldn't be using pkg_resources to retrieve the library.zip file. You should use it to retrieve the added resource.
Suppose you have the following project structure:
setup.py
foo/
__init__.py
bar.py
media/
image.jpg
You would use resource_string (or, preferably, resource_stream) to access image.jpg:
img = pkg_resources.resource_string(__name__, 'media/image.jpg')
That should "just work". At least it did when I bundled my media files in the EXE. (Sorry, I've since left the company where I was using py2exe, so don't have a working example to draw on.)
You could also try using pkg_resources.resource_filename(), but I don't think that works under py2exe.

Resources