configparser() issue in python with IDE Microsoft Code - python-3.x

Specs: Python version 3.7.3 (64-bit)
IDE Microsoft Code (latest edition as of 4/23)
Background I am having issues with executing my code with Configparser only on Microsoft code. I installed other IDE's pycharm etc and I do not have any issues. I prefer Microsoft Code interface / debugging so I would prefer to keep using it. I even went an extra step and installed MS-Code on another server and tried to exec my code with the exact same issue. On a side note if you execute the code in debug mode in ms-code it works without a key error.
This issue is really confusing to me and any help would be appreciated
Current structure of Configparser in code
config = configparser.ConfigParser()
config.read('api_config.ini')
#Reads in each of the api URLs to use from the config file
line_item_reporting = config['apis']['line_item_reporting']
line_item_meta = config['apis']['line_item_meta']
package_reporting = config['apis']['package_reporting']
package_meta = config['apis']['package_meta']
io_meta = config['apis']['io_meta']
io_reporting = config['apis']['io_reporting']
Error code
line_item_reporting = config['apis']['line_item_reporting']
File "C:\ProgramData\Anaconda3\lib\configparser.py", line 958, in getitem
raise KeyError(key)
KeyError: 'apis'
api_config.ini
[general]
meta_pull=50
num_loops=10
index_start=0
index_end=20
password=#######
lookback_window=3
[apis]
io_reporting = https://some_url
line_item_reporting = https://some_url
line_item_meta = https://some_url
package_reporting = https://some_url
package_meta = https://some_url
io_meta = https://some_url

Related

decodestrings is not an attribute of base64 error in python 3.9.1

After upgrading from python 3.8.0 to python 3.9.1, the tremc front-end of transmission bitTorrent client is throwing decodestrings is not an attribute of base64 error whenever i click on a torrent entry to check the details.
My system specs:
OS: Arch linux
kernel: 5.6.11-clear-linux
base64.encodestring() and base64.decodestring(), aliases deprecated since Python 3.1, have been removed.
use base64.encodebytes() and base64.decodebytes()
So i went to the site-packages directory and with ripgrep tried searching for the decodestring string.
rg decodestring
paramiko/py3compat.py
39: decodebytes = base64.decodestring
Upon examining the py3compat.py file,i found this block:
PY2 = sys.version_info[0] < 3
if PY2:
string_types = basestring # NOQA
text_type = unicode # NOQA
bytes_types = str
bytes = str
integer_types = (int, long) # NOQA
long = long # NOQA
input = raw_input # NOQA
decodebytes = base64.decodestring
encodebytes = base64.encodestring
So decodebytes have replaced(aliased) decodestring attribute of base64 for python version >= 3
This must be a new addendum because tremc was working fine in uptil version 3.8.*.
Opened tremc script, found the erring line (line 441), just replaced the attribute decodestring with decodebytes.A quick fix till the next update.
PS: Checked the github repository, and there's a pull request for it in waiting.
If you don't want to wait for the next release and also don't want to hack the way i did, you can get it freshly build from the repository, though that would be not much of a difference than my method

pyinstaller stops python from reading from script directory

I have this block of code that works in python script form but when I package the script to an exe using pyinstaller it always results in the program saying the config file can't be found. I put the config.ini in the same folder as the exe file.
config = configparser.ConfigParser()
configComplete = True
configExists = False
try:
open(os.path.join(sys.path[0],'config.ini'))
config.read(os.path.join(sys.path[0],'config.ini'))
destination = config['server']['ServerAddress']
key = config['server']['ApiKey']
configExists = True
except KeyError:
configComplete = False
except FileNotFoundError:
try:
open(expanduser('~/.config/octoprint-cli.ini'))
config.read(expanduser('~/.config/octoprint-cli.ini'))
destination = config['server']['ServerAddress']
key = config['server']['ApiKey']
configExists = True
except KeyError:
configComplete = False
except FileNotFoundError:
pass
I don't have python currently installed to test this on my machine, but typically when I am looking for a file that's relative to the python file location it's preferable to use:
import os
CONFIG_FILE_PATH = f"{os.path.dirname(__file__)}{os.sep}config.ini"
if os.path.exists(CONFIG_FILE_PATH): # If the file already exists
config.read(CONFIG_FILE_PATH) # Read it
else: # If a config file does not exist
# Either throw error or create fresh config
This code is an OS agnostic way of looking for a file in the same directory as the python file and the catching doesn't necessarily throw an error unless you want it to.
See if that works with pyinstaller, as I believe when I last used it this worked.

Python firebase_admin.credentials has no attribute Certificate

I'm currently developing for GCP and had used this code already many many times (this is running on RPI3 python 3.7)
def createClient(projid, dev_name):
base = os.getcwd()
base = base.replace("\\",'/')
keydir = '{}/Devices/{}/firebase.json'.format(base, projid.lower())
print(keydir)
cred = credentials.Certificate(keydir)
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://{}.firebaseio.com/'.format(projid.lower())
}, name= dev_name)
But now the code fails with message:
module 'firebase_admin.credentials' has no attribute 'Certificate'>
Please note this code it's working correctly in other RPI why is this not working?!
the error occurs in this line of code:
cred = credentials.Certificate(keydir)
anyone with a clue would be very very appreciated.
Kind Regards!
Edit: I've tried with:
cred = credentials.RefreshToken(keydir)
still the same result now with the error:
module 'firebase_admin.credentials' has no attribute 'RefreshToken'>
note I'm using a service account json file as a key.
Edit2: I missed to add this info in the original post:
firebase-admin==2.17.0
this is all running in a Raspberry Pi 3 B+ (RPI)

cx_freeze - How to change reference to lib

Building an Python application with cx_freeze.
from cx_Freeze import setup, Executable
_packages = []
_excludes = []
_include_files = [...]
buildOptions = dict(packages = _packages, enter code here`excludes = _excludes, include_files = _include_files, build_exe = '<app name>')
setup(name = '<app name>',
version = <version>,
description = '<description>',
options = dict(build_exe = buildOptions),
executables = [Executable('<app name>.py',
targetName = '<app name>',
icon = '<app name>.png')])
Attempting to install an application build with cx_freeze on Linux in /usr/bin/ with application resources in /usr/share/.
Of course this results in:
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module name 'encodings'
Current thread 0x0... (most recent call first):...
I think I need to set/change the default location of the lib folder but I have been unable to figure out how to do that. It's entirely possible that I might be on the completely wrong track.
I'm trying to avoid using bbfreeze.
After reviewing the code I believe what I want to do is not possible. The 'lib' directory is hard coded in cx_freeze.

How to get the default application mapped to a file extention in windows using Python

I would like to query Windows using a file extension as a parameter (e.g. ".jpg") and be returned the path of whatever app windows has configured as the default application for this file type.
Ideally the solution would look something like this:
from stackoverflow import get_default_windows_app
default_app = get_default_windows_app(".jpg")
print(default_app)
"c:\path\to\default\application\application.exe"
I have been investigating the winreg builtin library which holds the registry infomation for windows but I'm having trouble understanding its structure and the documentation is quite complex.
I'm running Windows 10 and Python 3.6.
Does anyone have any ideas to help?
The registry isn't a simple well-structured database. The Windows
shell executor has some pretty complex logic to it. But for the simple cases, this should do the trick:
import shlex
import winreg
def get_default_windows_app(suffix):
class_root = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, suffix)
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'{}\shell\open\command'.format(class_root)) as key:
command = winreg.QueryValueEx(key, '')[0]
return shlex.split(command)[0]
>>> get_default_windows_app('.pptx')
'C:\\Program Files\\Microsoft Office 15\\Root\\Office15\\POWERPNT.EXE'
Though some error handling should definitely be added too.
Added some improvements to the nice code by Hetzroni, in order to handle more cases:
import os
import shlex
import winreg
def get_default_windows_app(ext):
try: # UserChoice\ProgId lookup initial
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{}\UserChoice'.format(ext)) as key:
progid = winreg.QueryValueEx(key, 'ProgId')[0]
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'SOFTWARE\Classes\{}\shell\open\command'.format(progid)) as key:
path = winreg.QueryValueEx(key, '')[0]
except: # UserChoice\ProgId not found
try:
class_root = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, ext)
if not class_root: # No reference from ext
class_root = ext # Try direct lookup from ext
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'{}\shell\open\command'.format(class_root)) as key:
path = winreg.QueryValueEx(key, '')[0]
except: # Ext not found
path = None
# Path clean up, if any
if path: # Path found
path = os.path.expandvars(path) # Expand env vars, e.g. %SystemRoot% for ext .txt
path = shlex.split(path, posix=False)[0] # posix False for Windows operation
path = path.strip('"') # Strip quotes
# Return
return path

Resources