configparser.NoSectionError:No section:'XXX' - python

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

Related

KeyError after build PySimpleGUI exe

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 :)

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..

python3 error when passing variable into os.chdir

I am trying to find a specific pathname and pass this into os.chdir so I can run a command in that directory. I won't know the exact pathname hence why I have to run the find command. I have tried several ways to do this and each comes with a new error. The code below is one of the ways I have tried, can anyone suggest the best way to do this? Or how to fix this error?
Source Code:
import os
import subprocess
os.system('find ~ -path "*MyDir" > MyDir.txt')
output = subprocess.check_output("cat MyDir.txt", shell=True)
os.chdir(output)
os.system("file * > MyDir/File.txt")
The error:
Traceback (most recent call last):
File "sub1.py", line 8, in <module>
os.chdir(output)
FileNotFoundError: [Errno 2] No such file or directory: b'/Users/MyhomeDir/Desktop/MyDir\n'
I know that directory exists and presume it has something to do with the b' and \n'. I just don't know what the problem is.
Get rid of the \n with strip:
output = subprocess.check_output("cat MyDir.txt", shell=True).strip()
os.chdir(output)

libtorrent-python problems, "no such file or directory" when there clearly is

First of all, here's the code
#!/usr/bin/env python3.4
import libtorrent as lt
import os
fs = lt.file_storage()
lt.add_files(fs, "/var/mirror/packages/") # There are two files in this directory
t = lt.create_torrent(fs, flags = 1&8&16) # 1 = Optimization, 8 = Symbolic links, 16 = calculate file hashes.
t.add_tracker("udp://tracker.[private].com:80")
print(os.path.isdir("/var/mirror/packages/"))
lt.set_piece_hashes(t,"/var/mirror/packages/")
print(t.generate())
And here's what happens when I run it
True
Traceback (most recent call last):
File "./test.py", line 9, in <module>
lt.set_piece_hashes(t,"/var/mirror/packages/")
RuntimeError: No such file or directory
This is the page I got this from
I have browsed around the bindings, but I can't find the set_piece_hashes sources. It returns the same error code when I change the path to "." or "/" (keeping the add_files path the same)
Anyone know what I'm doing wrong? I can't find any sort of documentation other than the site I linked above
Turns out set_piece_hashes wants the parent directory of the directory you created the filestore with. After I fixed that, I now get another error, which is a known bug in libtorrent here

How to compile python code that uses boto to access S3?

I'm trying to compile a simple Python program, that uploads files to an S3 bucket using the boto package, in to a single, redistributable .exe file. I'm open to any compilation method. So far I've tried both bbfreeze and py2exe and both yield the same results. The code in question that causes trouble looks like this:
import boto
#...snip...
fname_base = os.path.basename(fname)
s3 = boto.connect_s3(aws_access_key_id=_aws_key, aws_secret_access_key=_aws_secret_key, is_secure=False);
bucket = s3.get_bucket(_bucket)
key = bucket.new_key(fname_base)
key.set_contents_from_filename(fname)
Compiled with either executable bundling utility and run I get:
Traceback (most recent call last):
File "s3stash.py", line 238, in <module>
sys.exit(main())
File "s3stash.py", line 225, in main
push_file_to_s3(f, options)
File "s3stash.py", line 160, in push_file_to_s3
_push_with_boto(fname)
File "s3stash.py", line 148, in _push_with_boto
s3 = boto.connect_s3(aws_access_key_id=_aws_key, aws_secret_access_key=_aws_secret_key, is_secure=False);
File "boto\__init__.pyo", line 104, in connect_s3
File "zipextimporter.pyo", line 82, in load_module
File "boto\s3\connection.pyo", line 27, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "boto\utils.pyo", line 55, in <module>
File "email\__init__.pyo", line 79, in __getattr__
ImportError: No module named multipart
I'm using ActiveState Python 2.6 on Windows XP SP3. The boto package was installed with:
easy_installer --always-unzip boto
I used the --always-unzip option based on the information found here about py2exe having issues with the egg files that were unpacked. Unfortunately the error I get is the same when I use bb-freeze to build the executable.
The output from py2exe includes, near the end, the following bit of information:
The following modules appear to be missing
['_scproxy', 'email.Encoders', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'simplejson']
Which lends some hints. I tried methods suggested in other posts to SO where the -i option was recommended when compiling with py2exe and unfortunately nothing helped. In those other questions the users were doing their own explicit inclusion of of the email sub-modules. I could not figure how to adapt those solutions to my case unfortunately and just adding them with -i didn't stop py2exe from warning me of the missing modules, or the resulting bundled exe from failing with the missing module error.
Can someone help me get this code bundled for redistribution?
I actually got this to work. The answer was to ditch boto and use the poster library instead. I still use boto to generate a signed policy and the necessary form fields for POST I do via poster, but the actual executable that does the POST only includes poster now. With just poster in the mix, py2exe doesn't have any issues creating a standalone executable for me for redistribution.
I know this is an old question, but I had the same problem and fixed it while still using py2exe and py2app. Just use the 'packages' option instead of the 'includes' option in your setup.py:
extra = {}
mainscript = "foo/__main__.py"
if is_os_x():
extra["setup_requires"] =['py2app']
extra["app"] = [mainscript]
extra["options"] = { "py2app": {
"packages": ['email'],
}
}
elif is_windows():
extra["setup_requires"] =['py2exe']
extra['console'] = [mainscript]
extra['options'] = {'py2exe': {
# Includes that py2exe doesn't include automatically
'packages': ['email'],
}
}
setup(
# snip
** extra
)
Hope that helps.
I've managed to create working exe with boto & py2exe
Add to your script.py
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
Next error is with HTTPS connection, it seems that py2exe is "hiding" cert file somehow..
The way to fix this is
1) use HTTP
OR
2) dont check certs
1) HTTP
conn = boto.connect_dynamodb(
aws_access_key_id = ' ',
aws_secret_access_key = ' ',
is_secure = False)
"is_secure = False" is crutial
2) DONT CHECK CERTS
conn = boto.connect_dynamodb(
aws_access_key_id = ' ',
aws_secret_access_key = ' ',
is_secure = True,
validate_certs = False)
"validate_certs = False" is crutial
If someone figures out how to fix error in cert validation, please reply !

Categories