i am trying to make a config file using ConfigParser in python 3.
I get this error when trying to run the script
C:\Users\Deagan>"C:\Users\Deagan\Desktop\Hypixel Rich Presence\Main.py"
Traceback (most recent call last):
File "C:\Users\Deagan\Desktop\Hypixel Rich Presence\Main.py", line 10, in <mod
ule>
APIKEY = config['DEFAULT']['secretid']
File "C:\Users\Deagan\AppData\Local\Programs\Python\Python38\lib\configparser.
py", line 1254, in __getitem__
raise KeyError(key)
KeyError: 'secretid'
Here is my config file:
[DEFAULT]
secretid = 'XXXXXXXXXX'
username = 'XXXX'
client_id = 'XXXXXXXX'
Here is the Main.py script file
config = ConfigParser()
config.read('config.ini')
APIKEY = config['DEFAULT']['secretid']
client_id = config['DEFAULT']['client_id']
username = config['DEFAULT']['username']
print(config.sections())
Am i doing something wrong?
Currently File not found error is not handled in config parser, check here https://github.com/jaraco/configparser/issues/53
Please check the config file is present in the same directory of python code.
To check file is present / not Move this Line to top,
print(config.sections())
If sections are printed then your file is ok check for typo in the section names and keys
Make sure the files are in the same folder and the name assigned to config.read('xxxxxx.ini') matches the one you created.
Related
I recieve some files with .ini file with them. I have to recieve file names from [FILES] section.
Sometimes there is an extra witespace in another section of .ini-file which raises exception in ConfigParser module
The example of "bad" ini-file:
[LETTER]
SUBJECT=some text
some text
and text with whitespace in the beggining
[FILES]
0=file1.txt
1=file2.doc
My code(Python 3.7):
import configparser
def get_files_from_ini_file(info_file):
ini = configparser.ConfigParser(allow_no_value=True)
ini.read(info_file) # ERROR is here
if ini.has_section("FILES"):
pocket_files = [ini.get("FILES", i) for i in ini.options("FILES")]
return pocket_files
print(get_files_from_ini_file("D:\\bad.ini"))
Traceback (most recent call last):
File "D:/test.py", line 10, in <module>
print(get_files_from_ini_file("D:\\bad.ini"))
File "D:/test.py", line 5, in get_files_from_ini_file
ini.read(info_file) # ERROR
File "C:\Users\ap\AppData\Local\Programs\Python\Python37-32\lib\configparser.py", line 696, in read
self._read(fp, filename)
File "C:\Users\ap\AppData\Local\Programs\Python\Python37-32\lib\configparser.py", line 1054, in _read
cursect[optname].append(value)
AttributeError: 'NoneType' object has no attribute 'append'
I can't influence on files I recieve so that is there any way to ignore this error? In fact I need only [FILES] section to parse.
Have tried empty_lines_in_values=False with no result
May be that's invalid ini file and I should write my own parser?
If you only need the "FILES" part, a simple way is to:
open the file and read into a string
get the part after "[FILES]" using .split() method
add "[FILES]" before the string
use the configparser read_string method on the string
This is a hacky solution but it should work:
import configparser
def get_files_from_ini_file(info_file):
with open(info_file, 'r') as file:
ini_string = file.read()
useful_part = "[FILES]" + ini_string.split("[FILES]")[-1]
ini = configparser.ConfigParser(allow_no_value=True)
ini.read_string(useful_part) # ERROR is here
if ini.has_section("FILES"):
pocket_files = [ini.get("FILES", i) for i in ini.options("FILES")]
return pocket_files
print(get_files_from_ini_file("D:\\bad.ini"))
I'm starting on a project using Clarifai. However, when I define the app, I'm getting a key error:
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage
import os
from glob import glob
api_key = 'my api key'
app = ClarifaiApp(api_key=api_key) # Error occurs here
model_id = 'model id'
concepts = ['concept1', 'concept2', 'concept3']
Traceback (most recent call last):
File "C:\Users\crayo\uShoe\main.py", line 6, in <module>
app = ClarifaiApp(api_key=api_key)
File "C:\Users\user\project\venv\lib\site-packages\clarifai\rest\client.py", line 124, in __init__
self.models = Models(self.api, self.solutions) # type: Models
File "C:\Users\user\project\venv\lib\site-packages\clarifai\rest\client.py", line 1068, in __init__
self.model_id_cache = self.init_model_cache()
File "C:\Users\user\project\venv\lib\site-packages\clarifai\rest\client.py", line 1088, in init_model_cache
model_type = m.output_info['type']
KeyError: 'type'
I'm not sure what's causing this error, so if someone could provide input I'd appreciate it! Thanks!
You are using the deprecated Python REST package: https://github.com/Clarifai/clarifai-python. Please replace your code with the new & updated Python gRPC client: https://github.com/Clarifai/clarifai-python-grpc
Make sure to uninstall the REST package to avoid conflicts.
You can find our API docs & code snippets here: https://docs.clarifai.com
I wanted to explore Google Big-Query with Python, and as per this tutorial I have set up a Google Cloud Account (free-tier), and have generated a key. The JSON file is stored in D:\keys\quixotic-folio-318907-64bfdccfb050.json.
The ENVIRONMENT VARIABLES in Windows-10 is also added under GOOGLE_APPLICATION_CREDENTIALS under System Variables:
However, whenever I try to initialize the client, it throws an error - File Not Found:
> from google.cloud import storage
> storage.Client(project = "quixotic-folio-318907")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Anaconda3\lib\site-packages\google\cloud\storage\client.py", line 123, in __init__
super(Client, self).__init__(
File "D:\Anaconda3\lib\site-packages\google\cloud\client.py", line 319, in __init__
Client.__init__(
File "D:\Anaconda3\lib\site-packages\google\cloud\client.py", line 178, in __init__
credentials, _ = google.auth.default(scopes=scopes)
File "D:\Anaconda3\lib\site-packages\google\auth\_default.py", line 454, in default
credentials, project_id = checker()
File "D:\Anaconda3\lib\site-packages\google\auth\_default.py", line 221, in _get_explicit_environ_credentials
credentials, project_id = load_credentials_from_file(
File "D:\Anaconda3\lib\site-packages\google\auth\_default.py", line 107, in load_credentials_from_file
raise exceptions.DefaultCredentialsError(
google.auth.exceptions.DefaultCredentialsError: File D:\keys\quixotic-folio-318907-64bfdccfb050.json; was not found.
I've tried os method, as suggested here, and it is running perfectly:
> import os
> from google.cloud import storage
> os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "D:\keys\quixotic-folio-318907-64bfdccfb050.json"
> storage.Client(project = "quixotic-folio-318907")
<google.cloud.storage.client.Client object at 0x000002448A4E8AF0>
I have the following questions:
Is this an expected behavior, and why?
How do I ensure that I do not have to specifically set os.environ['GOOGLE_APPLICATION_CREDENTIALS'] as it is already defined under System Variables?
Remove the
;
at the end of your path in the environment variable.
Edit: User AKS was faster than me. #AKS: If you write your comment in an answer, it can be marked as solved.
I am trying to use PyGitHub to automate updating files in a special repository. This special repo consists of parts of several other repos so I am using a GitHub webhook to cause it to be updated whenever any of the other repos are updated. I am running into a problem when a file is added to any of the other repos. In this case, I need to add a file to the special repo. Here is a snippet of the code
from github import GitHub
ACCESS_TOKEN = '...'
ORGANIZATION = '...'
REPONAME = '...'
gh = Github(ACCESS_TOKEN)
org = gh.get_organization(ORGANIZATION)
repo = org.get_repo(REPONAME)
path = <path-to-file-in-special-repo>
message = <commit-message-for-create-file>
contents = OtherRepo.get_contents(<<path-to-file-in-other-repo>).decoded_content.decode('utf-8')
repo.create_file(path, message, contents)
This is giving me the following error:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/local/lib/python3.9/site-packages/github/Repository.py", line 2090, in create_file
headers, data = self._requester.requestJsonAndCheck(
File "/usr/local/lib/python3.9/site-packages/github/Requester.py", line 353, in requestJsonAndCheck
return self.__check(
File "/usr/local/lib/python3.9/site-packages/github/Requester.py", line 378, in __check
raise self.__createException(status, responseHeaders, output)
github.GithubException.GithubException: 422 {"message": "Invalid request.\n\n\"sha\" wasn't supplied.", "documentation_url": "https://docs.github.com/rest/reference/repos#create-or-update-file-contents"}
If I just do:
repo.create_file(path, 'test', 'test')
it works.
Can anyone tell me what I am doing wrong?
I have discovered what the problem is.
Because of the way I was testing my program the file I was trying to create was one previously deleted from the repo. What I needed to do was repo.update_file and, not repo.create_file.
I've just started today to code! so please be kind! :D
After a long we to install programs and libraries in coding my fist "trading bot"
I'm trying to connect to my test-api in Binance but I have an issue.
Here my lines of coding
Here my error that i cant fix [syntax error][2]
Ive already done:
uninstall and install again pip python-binance
install conda twisted
install pip update same packages
Any suggestions?
Many thanks
--- edit
photo of errors
ive tried all 3 types of suggestion
now pythons tell me there there is no module named 'binance' how is possible?
- relevant code
# Importing libraries
from binance.client import Client
import configparser
# Loading keys from config file
config = configparser.ConfigParser()
config.read_file(open('<C:\\Users\\ssida\\OneDrive\\Documenti\\GitHub\\AI7XF205SS\\secret.cfg>'))
test_api_key = config.get('BINANCE', 'TEST_API_KEY')
test_secret_key = config.get('BINANCE', 'TEST_SECRET_KEY')
client = Client(test_api_key, test_secret_key)
client.API_URL = 'https://testnet.binance.vision/api' # To change endpoint URL for test account
info = client.get_account() # Getting account info
print(info)
edit 2x ---
i think che path now works, but now i have a new issue... PI Error (code+-2014).. gonna search what is that..
seems that API key format is invalid :(
[Running] python -u "c:\Users\ssida\OneDrive\Documenti\GitHub\AI7XF205SS\getting_account_info.py"
Traceback (most recent call last):
File "c:\Users\ssida\OneDrive\Documenti\GitHub\AI7XF205SS\getting_account_info.py", line 15, in <module>
info = client.get_account() # Getting account info
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 1822, in get_account
return self._get('account', True, data=params)
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 292, in _get
return self._request_api('get', path, signed, version, **kwargs)
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 242, in _request_api
return self._request(method, uri, signed, **kwargs)
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 237, in _request
return self._handle_response()
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 285, in _handle_response
raise BinanceAPIException(self.response)
binance.exceptions.BinanceAPIException: APIError(code=-2014): API-key format invalid.
[Done] exited with code=1 in 1.944 seconds
The problem is the backslash is a special character (ex \n marks a new line)
You can fix this by either adding r before the path
r'C:\Users\...'
or change the backslash with double ones
'C:\\Users\\...'
or replace with '/'
'C:/Users/...'
EDIT
Remove the '<>' from the start and end of the path because open takes it as it is