os.environ producing error recently only? - python

Recently I had this problem with vscode where os.environ isn't working anymore, it used to be able to read the key on the separate .env file. This file works perfect on replit, however, when i try downloading it, it can't be run locally
I have tried deleting .pyc files, but it's still the same.
Python os.environ throws key error?
Error in the terminal:
Traceback (most recent call last):
File "c:\Users\heroku\Desktop\ricebot\main.py", line 62, in <module>
my_secret = os.environ['TOKEN']
File "C:\Users\heroku\AppData\Local\Programs\Python\Python39\lib\os.py", line 679, in __getitem__
raise KeyError(key) from None
KeyError: 'TOKEN'

Related

xlwings Reports Quickstart throws errors

Just trying the quickstart described here:
https://docs.xlwings.org/en/stable/reports.html#quickstart
I've copied the small code sample and created the template sheet as described. When I run report.py, I get the following:
Traceback (most recent call last):
File "report.py", line 17, in <module>
book = app.render_template(this_dir / 'mytemplate.xlsx',
File "/home/james/dev/repos/eft/auto-reports/env/lib/python3.8/site-packages/xlwings/main.py", line 699, in render_template
return render_template(
File "/home/james/dev/repos/eft/auto-reports/env/lib/python3.8/site-packages/xlwings/pro/reports/main.py", line 439, in render_template
wb = app.books.open(output)
File "/home/james/dev/repos/eft/auto-reports/env/lib/python3.8/site-packages/xlwings/main.py", line 4988, in open
return Book(impl=self.impl.open(json=json))
File "/home/james/dev/repos/eft/auto-reports/env/lib/python3.8/site-packages/xlwings/pro/_xlremote.py", line 217, in open
book = Book(api=json, books=self)
File "/home/james/dev/repos/eft/auto-reports/env/lib/python3.8/site-packages/xlwings/pro/_xlremote.py", line 268, in __init__
if api["version"] != __version__:
TypeError: 'NoneType' object is not subscriptable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "report.py", line 20, in <module>
book.to_pdf(this_dir / 'myreport.pdf')
File "/home/james/dev/repos/eft/auto-reports/env/lib/python3.8/site-packages/xlwings/main.py", line 764, in __exit__
self.quit()
File "/home/james/dev/repos/eft/auto-reports/env/lib/python3.8/site-packages/xlwings/main.py", line 388, in quit
return self.impl.quit()
File "/home/james/dev/repos/eft/auto-reports/env/lib/python3.8/site-packages/xlwings/base_classes.py", line 50, in quit
raise NotImplementedError()
NotImplementedError
This is essentially out of the box so I can't see that I've done anything wrong. I'm running on Ubuntu 20.04.5 LTS. Python is 3.8.10. I have the follwing dependencies:
numpy==1.23.4
pandas==1.5.1
python-dateutil==2.8.2
pytz==2022.5
six==1.16.0
xlwings==0.28.2
Any suggestions? Thanks.
Traditionally, xlwings only worked on Windows or macOS with an actual installation of Microsoft Excel. More recently (in 2022) it added Linux support for xlwings Server and xlwings File Reader, but xlwings Reports still has to be run in connection with Excel, i.e., runs on Windows and macOS only. While the installation instructions mention this, I'll try to improve the docs to mark the requirements on the respective pages.

Cannot access token.json: No such file or directory Python

I'm trying to access the Gmail API via Python. Here is the instruction.
I have copied the credentials.json (I have also renamed a copy of it and called it token.json and added it into the main folder) and the quickstart.py files in the main folder. I run the quickstart.py in the cmd and using Atom IDE, but I get:
C:\Users\HP Pavilion\AppData\Local\Programs\Python\Python36\lib\site-packages\oauth2client\_helpers.py:255: UserWarning: Cannot access token.json: No such file or directory
warnings.warn(_MISSING_FILE_MESSAGE.format(filename))
Traceback (most recent call last):
File "C:\Users\HP Pavilion\AppData\Local\Programs\Python\Python36\lib\site-packages\oauth2client\clientsecrets.py", line 121, in _loadfile
with open(filename, 'r') as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'credentials.json'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\HP Pavilion\Documents\Atom\Gmail\quickstart.py", line 34, in <module>
main()
File "C:\Users\HP Pavilion\Documents\Atom\Gmail\quickstart.py", line 18, in main
flow = client.flow_from_clientsecrets("credentials.json", SCOPES)
File "C:\Users\HP Pavilion\AppData\Local\Programs\Python\Python36\lib\site-packages\oauth2client\_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Users\HP Pavilion\AppData\Local\Programs\Python\Python36\lib\site-packages\oauth2client\client.py", line 2135, in flow_from_clientsecrets
cache=cache)
File "C:\Users\HP Pavilion\AppData\Local\Programs\Python\Python36\lib\site-packages\oauth2client\clientsecrets.py", line 165, in loadfile
return _loadfile(filename)
File "C:\Users\HP Pavilion\AppData\Local\Programs\Python\Python36\lib\site-packages\oauth2client\clientsecrets.py", line 125, in _loadfile
exc.strerror, exc.errno)
oauth2client.clientsecrets.InvalidClientSecretsError: ('Error opening file', 'credentials.json', 'No such file or directory', 2)
Seems like the .json files can't be found. They are however in the same folders. I have also tried to run the code as an administrator but without any success.
I am not sure what happened to you but I run the script with either PyCharm or VS Code and it runs perfectly.
The only prerequisite (probably you skipped this step) is that you should first generate the credentials.json file, download it and put it into the same directory where you have the python script. In addition, I created an empty tokens.json file.
First, it will automatically open your default browser to indicate which Gmail account you want to specify. Next, it will output the labels of your Gmail account.
My mistake was that I right clicked on my JSON file, selected rename, then named it credentials.JSON, which made the real file name credentials.JSON.JSON.
If it is in the same location as the script, you can try:
import os
path = os.path.abspath('credentials.json')
with open(path,'r'):
//code
I had the same issue and it turned out that the problem was with the IDE I'm using (Mu 1.1.0). Once I downloaded the JSON file, renamed it, placed it in the directory to where the error was pointing to, and ran everything with cmd, it worked as it should.

the outdated script is being executed according to Python traceback

I've encountered a weird issue regrading the tracebacks in python. I've updated some code but while debugging, it's still using the outdated code. detailed traceback as below:
Error: Traceback (most recent call last):
File "~/myenv/lib/python2.7/site-packages/xxx/xmlrpc/dispatcher.py", line 95, in _marshaled_dispatch
response = self._dispatch(method, params)
File "/usr/lib64/python2.7/SimpleXMLRPCServer.py", line 420, in _dispatch
return func(*params)
File "~/myenv/lib/python2.7/site-packages/kobo/hub/decorators.py", line 24, in _new_func
return func(request, *args, **kwargs)
File "~/myenv/lib/python2.7/site-packages/myapp/worker.py", line 61, in register
download.save()
I'm pretty sure the exception thrown by download.save() is already removed. i.e., the line 61 in ~/myenv/lib/python2.7/site-packages/myapp/worker.py doesn't contain download.save():
$ grep -r "download.save" ~/myenv/lib/python2.7/site-packages/myapp/
no matchings found.
but it looks python still uses the out-dated code. my new changes still won't work.
besides, I've also removed the worker.pyc file under the save directory before running the scripts.
any ideas how to resolve the issue?
When you grep, and when you run the code, are they as the same user? Is the code running under a web server or similar daemon process, with a different username and a different home directory?
What if you remove all precompiled .pyc files?

Python ImportError: No module named - Works in ssh but not in browser

Not sure what the issue is. Works fine via ssh. When viewed in a browser I get a server error. This is know working code that has been migrated to another server / environment.
It can not find a module that is clearly in the directory. Have checked permissions on files and they look ok 755.
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator to inform of the time the error occurred and of anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
ImportError: No module named xmlproducts
mod_python (pid=16232, interpreter='realtechy.com', phase='PythonHandler', handler='mod_python.cgihandler'): Application error
ServerName: 'realtechy.com'
DocumentRoot: '/var/www/vhosts/realtechy.com/httpdocs'
URI: '/products/myproducts.py'
Location: None
Directory: '/var/www/vhosts/realtechy.com/httpdocs/'
Filename: '/var/www/vhosts/realtechy.com/httpdocs/products/myproducts.py'
PathInfo: ''
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/mod_python/importer.py", line 1537, in HandlerDispatch\n default=default_handler, arg=req, silent=hlist.silent)
File "/usr/lib/python2.6/site-packages/mod_python/importer.py", line 1229, in _process_target\n result = _execute_target(config, req, object, arg)
File "/usr/lib/python2.6/site-packages/mod_python/importer.py", line 1128, in _execute_target\n result = object(arg)
File "/usr/lib/python2.6/site-packages/mod_python/cgihandler.py", line 96, in handler\n imp.load_module(module_name, fd, path, desc)
File "/var/www/vhosts/realtechy.com/httpdocs/products/myproducts.py", line 6, in <module>\n import xmlproducts
ImportError: No module named xmlproducts
Sounds like the module is not installed properly (or at all). To verify, do the following:
open a shell and start the python shell by typing python
enter the commmand help('modules')
review the list of modules that's returned to see whether xmlproducts is included
if not, then install the module

Error 500 executing python script

I recently re-installed my Ubuntu PC (to 12.04) & had to re-setup apache.
local.domain.com points to localhost (virtual host).
http://local.domain.com/script.py?query=string
script.py is chmod'd to 755.
In my .htaccess I have :
Options +ExecCGI
AddHandler cgi-script .py
But I get a 500 : Internal Server Error.
cat /var/log/apache2/error.domain.com.log shows nothing.
If I do python script.py in the command line I get :
<!-- The above is a description of an error in a Python program, formatted
for a Web browser because the 'cgitb' module was enabled. In case you
are not reading this in a Web browser, here is the original traceback:
Traceback (most recent call last):
File "script.py", line 32, in <module>
queryHash = hashlib.sha224(os.environ['QUERY_STRING']).hexdigest()
File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__
raise KeyError(key)
KeyError: 'QUERY_STRING'
-->
So I don't figure anything wrong with the py script. It used to work before.
But for some reason its not executing in the browser.
What else could I have missed ?
The error is right there infront of you:
Traceback (most recent call last):
File "script.py", line 32, in <module>
queryHash = hashlib.sha224(os.environ['QUERY_STRING']).hexdigest()
File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__
raise KeyError(key)
KeyError: 'QUERY_STRING'
Which says it can't access the key QUERY_STRING. It even gives you the exact line of code that the error occurred at:
File "script.py", line 32
queryHash = hashlib.sha224(os.environ['QUERY_STRING']).hexdigest()
The environment variable QUERY_STRING has not been set for the apache user. How did you have this set before? You might need to set it in the httpd profile, and for Ubuntu, I'm not sure where that is.
Ubuntu 12.04 has python 2.7. My script's shebang line was :
#!/usr/bin/env python2.6

Categories

Resources