KeyError after build PySimpleGUI exe - python

I've trying to build exe for my PySimpleGui project. Problem is that when I start exe it give me error, but can't figure out why. Do I need to make some special magics when I use config.cfg file as my project folder root where project.py is?
File "project.py", line 46, in <module>
KeyError: 'CONF'
[21352] Failed to execute script 'project' due to unhandled exception!
My code related for line 46:
currentFile = __file__
realPath = os.path.realpath(currentFile)
dirPath = os.path.dirname(realPath)
dirName = os.path.basename(dirPath)
config = configparser.RawConfigParser()
config.read(dirPath + '/config.cfg')
def get_config_section():
if not hasattr(get_config_section, 'section_dict'):
get_config_section.section_dict = collections.defaultdict()
for section in config.sections():
get_config_section.section_dict[section] = dict(config.items(section))
return get_config_section.section_dict
config_dict = get_config_section()
# Values...
main_conf = config_dict['CONF']['key']

Did you run the code before compiling it ?
Do you have the latest version of pyinstaller installed.
Try running the code and seeing the error
Hope this helps :)

Related

Instabot KeyError: 'urlgen'

im trying to do a instagram bot but i just could run the code once, and it worked fine but when i tried again it dropped me this error
i wont write my user and pass in this question obviously haha
from instabot import *
session = Bot()
session.login(username = "myuser",
password = "mypass")
and i get this error
2021-02-01 16:07:42,401 - INFO - Instabot version: 0.117.0 Started
Traceback (most recent call last):
File "C:/Users/EQUIPO/Desktop/5 CUATRI/Phyton/Ejercicios Prueba/nsoe.py", line 3, in <module>
session.login(username = "nota.niceplace",
File "C:\Program Files\Python38\lib\site-packages\instabot\bot\bot.py", line 443, in login
if self.api.login(**args) is False:
File "C:\Program Files\Python38\lib\site-packages\instabot\api\api.py", line 240, in login
self.load_uuid_and_cookie(load_cookie=use_cookie, load_uuid=use_uuid)
File "C:\Program Files\Python38\lib\site-packages\instabot\api\api.py", line 199, in load_uuid_and_cookie
return load_uuid_and_cookie(self, load_uuid=load_uuid, load_cookie=load_cookie)
File "C:\Program Files\Python38\lib\site-packages\instabot\api\api_login.py", line 354, in load_uuid_and_cookie
self.cookie_dict["urlgen"]
KeyError: 'urlgen'
You need to delete config folder which is automatically created by system when you run this code first time.
So you need to delete this folder every time before run your code.
This config folder is in same directory where your file is saved.
I had same problem and i am able to solve by this way.
This code will fix everything automatically for you just change image name and path.
from instabot import Bot
import os
import shutil
def clean_up(i):
dir = "config"
remove_me = "imgs\{}.REMOVE_ME".format(i)
# checking whether config folder exists or not
if os.path.exists(dir):
try:
# removing it so we can upload new image
shutil.rmtree(dir)
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
if os.path.exists(remove_me):
src = os.path.realpath("imgs\{}".format(i))
os.rename(remove_me, src)
def upload_post(i):
bot = Bot()
bot.login(username="your_username", password="your_password")
bot.upload_photo("imgs/{}".format(i), caption="Caption for the post")
if __name__ == '__main__':
# enter name of your image bellow
image_name = "img.jpg"
clean_up(image_name)
upload_post(image_name)
As Raj said. You need to delete the config folder like this from where you ran the python script. Sorry for making a separate answer but for me it was not immediate clear where this config folder was so I thought it might help.
rm -rf config
Unfortunately the library is quite poor with their error messages
Unfortunately, it seems that instabot library's maintenance is down, don't try to run anything using that lib, won't work, and might, as commented by some users, compromise your account! sorry..

Path issue to root directory

I am currently trying to run the coin_flip_traders_v1.0.py script from the Darwinex ZeroMQ Python library here -> https://github.com/darwinex/dwx-zeromq-connector/tree/master/v2.0.1/python
However, I am having some trouble with the path that it says at the top of the file to point to the root directory.
I have changed it to _path = '../../..' Which should take me to the project root. However I get the error:
File
"/Users/Al/Desktop/Trading/examples/template/strategies/base/DWX_ZMQ_Strategy.py",
line 20, in os.chdir(_path) NameError: name '_path' is not defined
I then changed the path for the DWX_ZMQ_Strategy.py to _path = '../../../..'
I then get the error:
File
"/Users/Al/Desktop/Trading/examples/template/strategies/base/DWX_ZMQ_Strategy.py",
line 24, in from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import
DWX_ZeroMQ_Connector ModuleNotFoundError: No module named 'api'
I am thinking that it has something to do with the way I am setting the path to the root directory, but not sure where I am going wrong.
If it helps, I am running python 3.6.8 and the command I am executing to run the script is exec(open("coin_flip_traders_v1.0.py").read())
The problem is not a ZeroMQ-related problem.
For diagnosing the rest, the successful file-system tree-navigation, start with using this:
print( "DEBUG: now uses this directory-tree {0:} node".format( os.getcwd ) )
...
os.chdir( anyMaskForRelativeOrAbsoluteTreeMOVE ) # no ~-"expansions"
...
print( "DEBUG: now uses this directory-tree {0:} node".format( os.getcwd ) )
Also kindly note, you must reach such a directory, where the API was installed, not the "root"-directory of the whole filesystem. Check where your DWX installation is actually located and direct the os.chdir()-move to reach that point.

configparser.NoSectionError:No section:'XXX'

I want to configure a config. ini and read it. When I run the code in pycharm, it's okay and it returns the result normally. But when I use pyinstaller to package .PY into an .EXE file, it will report an error:
Congparser.NosectionError: No section:'config'
If there are any suggestions, I would be very grateful.
By the way, the. EXE file and. INI file are in the same folder,
I use Python3.7 on Windows10
I'm a Python rookie. I don't know how to solve the error in cmd. I try to output the path in pycharm. The result is very normal.
# coding = gbk
import configparser
import os
curpath = os.path.dirname(os.path.realpath(__file__))
cfgpath = os.path.join(curpath, "config.ini")
print(cfgpath)
print(os.path.realpath(__file__))
conf = configparser.ConfigParser()
conf.read(cfgpath)
items = conf.items('config')
l2 = [items[0][1],items[1][1],items[2][1],items[3][1]]
print(items)
print(l2)
Results in pycharm:
E:\untitled\venv\Custom_formula\config.ini
E:\untitled\venv\Custom_formula\config_data.py
[('server', '127.0.0.1'), ('user', 'sa'), ('pwd', '123456'), ('db', 'test')]
['127.0.0.1', 'sa', '123456', 'test']
Results in CMD:
Traceback (most recent call last):
File "config_data.py", line 25, in <module>
File "configparser.py", line 848, in items
configparser.NoSectionError: No section: 'config'
[9080] Failed to execute script config_data
Thanks for Rolf of Saxony! I solved this problem by change
curpath = os.path.dirname(os.path.realpath(__file__))
to
curpath = os.path.dirname(os.path.realpath(sys.argv[0]))
it turns out that the resluts in pycharm are different from those in EXE,
hopefully this will help more people

keyring module is not included while packaging with py2exe

I am making an app using python 2.7 on windows and keyring-3.2.1 . In my python code on eclipse, I used
import keyring
keyring.set_password("service","jsonkey",json_res)
json_res= keyring.get_password("service","jsonkey")
is working fine as I am storing json response in keyring. But, when I converted python code into exe by using py2exe, it shows import error keyring while making dist. Please suggest how to include keyring in py2exe.
Traceback (most recent call last):
File "APP.py", line 8, in <module>
File "keyring\__init__.pyc", line 12, in <module>
File "keyring\core.pyc", line 15, in <module>
File "keyring\util\platform_.pyc", line 4, in <module>
File "keyring\util\platform.pyc", line 29, in <module>
AttributeError: 'module' object has no attribute 'system'
platform_.py code is :
from __future__ import absolute_import
import os
import platform
def _data_root_Windows():
try:
root = os.environ['LOCALAPPDATA']
except KeyError:
# Windows XP
root = os.path.join(os.environ['USERPROFILE'], 'Local Settings')
return os.path.join(root, 'Python Keyring')
def _data_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine storage
location.
"""
fallback = os.path.expanduser('~/.local/share')
root = os.environ.get('XDG_DATA_HOME', None) or fallback
return os.path.join(root, 'python_keyring')
# by default, use Unix convention
data_root = globals().get('_data_root_' + platform.system(), _data_root_Linux)
platform.py code is:
import os
import sys
# While we support Python 2.4, use a convoluted technique to import
# platform from the stdlib.
# With Python 2.5 or later, just do "from __future__ import absolute_import"
# and "import platform"
exec('__import__("platform", globals=dict())')
platform = sys.modules['platform']
def _data_root_Windows():
try:
root = os.environ['LOCALAPPDATA']
except KeyError:
# Windows XP
root = os.path.join(os.environ['USERPROFILE'], 'Local Settings')
return os.path.join(root, 'Python Keyring')
def _data_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine storage
location.
"""
fallback = os.path.expanduser('~/.local/share')
root = os.environ.get('XDG_DATA_HOME', None) or fallback
return os.path.join(root, 'python_keyring')
# by default, use Unix convention
data_root = globals().get('_data_root_' + platform.system(), _data_root_Linux)
The issue you're reporting is due to an environment that contains invalid modules, perhaps from an improper installation of one version of keyring over another. You will want to ensure that you've removed remnants of the older version of keyring. In particular, make sure there's no file called keyring\util\platform.* in your site-packages.
After doing that, however, you'll encounter another problem. Keyring loads its backend modules programmatically, so py2exe won't detect them.
To work around that, you'll want to add a 'packages' declaration to your py2exe options to specifically include the keyring.backends package. I invoked the following setup.py script with Python 2.7 to convert 'app.py' (which imports keyring) to an exe:
from distutils.core import setup
import py2exe
setup(
console=['app.py'],
options=dict(py2exe=dict(
packages='keyring.backends',
)),
)
The resulting app.exe will import and invoke keyring.

Using psyco with py2exe?

In my main script, lets call this MyScript.py, I have it like this:
import psyco
psyco.full()
And then my setup.py looks like this:
from distutils.core import setup
import py2exe, sys, os, glob
sys.argv.append('py2exe')
import psyco #speed up compilation
psyco.full()
def find_data_files(source,target,patterns):
"""Locates the specified data-files and returns the matches
in a data_files compatible format.
source is the root of the source data tree.
Use '' or '.' for current directory.
target is the root of the target data tree.
Use '' or '.' for the distribution directory.
patterns is a sequence of glob-patterns for the
files you want to copy.
"""
if glob.has_magic(source) or glob.has_magic(target):
raise ValueError("Magic not allowed in src, target")
ret = {}
for pattern in patterns:
pattern = os.path.join(source,pattern)
for filename in glob.glob(pattern):
if os.path.isfile(filename):
targetpath = os.path.join(target,os.path.relpath(filename,source))
path = os.path.dirname(targetpath)
ret.setdefault(path,[]).append(filename)
return sorted(ret.items())
setup(
name="MyScript",
version="1.0",
description="a script that does something",
author="Keelx",
data_files=find_data_files('.','',[
'gfx/*',
'data/*',
]),
options={'py2exe': {'bundle_files': 1,'optimize': 2}},
windows=[{'script': "MyScript.py"}],
zipfile=None,
)
It creates a 'dist' folder, with the executable, a win9x executable, and the gfx and data folders next to the executable. However, when I run it it points me to a log which reads:
Traceback (most recent call last):
File "MyScript.py", line 16, in
File "zipextimporter.pyo", line 82, in load_module
File "psyco__init__.pyo", line 64, in
WindowsError: [Error 3] The system cannot find the path specified: 'C:\Documents and Settings\Keelx\Desktop\MyScriptFolder\dist\MyScript.exe\psyco\_psyco.pyd'
It would seem that the psyco module is not being put into the executable. I've been searching, and I haven't found a working solution to get py2exe to copy psyco over.
And please refrain from posting solutions along the lines of 'don't use py2exe'.
Thank you in advance whomever can help me out here.
Hunting down py2exe errors appears to be an art to me.
That said, I will at least offer something to try.
I py2exe'ed a psyco enabled python script and tossed it in the includes part of the setup.
Thats the only part that looks different between your setup and my old one.
options = {'py2exe': {'packages': [ 'IPython'],
'includes': ["psyco"],
}
}
Also I was never able to enable optimize. It always caused random errors. Best to leave that one off in my experience. I think it was matplotlib that caused those errors.
Hope this helps,
Cheers,

Categories