ValueError: bad file descriptor - python-3.x

I'm trying to write a script in which I need to get the terminal size in order to adjust the output text width appropriately. I use this lines:
import os
x = os.get_terminal_size().lines
which results in getting this error:
ValueError: bad file descriptor
What's wrong with the code?

Try this:
import sys
import os
try:
cols,rows = os.get_terminal_size(0)
except OSError:
cols,rows = os.get_terminal_size(1)
sys.stdout.write('cols:{} \n rows:{} \n'.format(cols,rows))

Check out this page you can find multiple example with error handling

Related

'Fata Error ' : Python executable throwing error

I have a 'working' Python code, TCP_Barcode_V1.py which read a text file and gives output in a tkinter window.
However, if I convert the Python file to an .exe using auto-py-to-exe, when executing TCP_Barcode_V1.exe, am getting error like fatal error occurred Failed to execute script TCP_Barcode_V1 in a messagebox
my text file, param.txt looks like this :
192.1.22.43
6666
3000
each line is read and stored in a variable
In my python file, am reading the file as
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
my_file = os.path.join(THIS_FOLDER, 'param.txt')
with open(my_file, "r") as fp:
val = [line.strip() for line in fp]
duration = int(val[0])
TCP_IP = val[1]
TCP_PORT = int(val[2])
Can someone identify what the problem here is.
Please note that the original TCP_Barcode_V1.py is working without any issues. And also, I am using the same device for running the .py as well as .exe file.
below is my auto-py-to-exe settings I chose

sqlite3.OperationalError: unable to open database file - error occurs after a certain while

Tooling:
Raspberry Pi 3B
Raspbian
BME280
Python3
Flask
Sqlite3
Error code:
Traceback (most recent call last):
File "BME280_DataCollector.py", line 65, in <module>
File "BME280_DataCollector.py", line 45, in logData
sqlite3.OperationalError: unable to open database file
Working on Raspbian and want to store my sensor data in sqlite3 database.
Somehow following error code occurs:
"sqlite3.OperationalError: unable to open database file".
Firstly, I thought that I requested the database file too quickly and changed the the measurement time to minutes, but the error is still reproducible.
I looked into /tmp by df /tmp. But this file system is used by 12 % and not overloaded.
Also, I tried to give the full path and also the database all write and read permissions via chmod, but also no differents. In addition, I put the full path to the code.
Furthermore, I tried to make try and exception approaches which also weren't fruitful.
Nevertheless, I wanted to know if this failure occures at a certain number of interactions with the database. I found out that it always stopped at the 1020th interaction.
I also tried to restart the python script with a shell script but it didn't work out due to lack of experience and knowledge.
Code:
from flask import Flask,render_template,url_for,request,redirect, make_response, send_file
import random
import json
from time import sleep
from random import random
from flask import Flask, render_template, make_response
import datetime
import sqlite3
import sys
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import io
import os
import smbus2
import bme280
## FUNCTIONS ##
# get data
def getBMEdata():
port = 1
adress = 0x77
bus = smbus2.SMBus(port)
calibration_params = bme280.load_calibration_params(bus, adress)
bme_data = bme280.sample(bus, adress, calibration_params)
temp = '%.2f' % bme_data.temperature
hum = '%.2f' % bme_data.humidity
press = '%.2f' % bme_data.pressure
now = datetime.datetime.now() #get time
timeString = now.strftime('%d-%m-%Y %H:%M:%S') #write time to string
return temp, hum, press, timeString
# function to insert data on a table
def logData(temp, hum, press, timeString):
conn = sqlite3.connect(dbname)
curs = conn.cursor()
curs.execute("INSERT INTO BME280_data values((?), (?), (?), (?))", (timeString, temp, hum, press))
conn.commit()
conn.close()
# display data base
def displayData():
conn = sqlite3.connect(dbname)
curs = conn.cursor()
print("\nEntire database contents:\n")
for row in curs.execute("SELECT * FROM BME280_data"):
print(row)
conn.close()
## MAIN
if __name__ == '__main__':
count = 0
dbname = '/home/pi/projects/SmartPlanting/Sensors_Database/sensorsData.db'
sampleFreq = 60 #data collect every minute
while True:
temp, hum, press, timeString = getBMEdata() #get data
logData(temp, hum, press, timeString) #save data
sleep(sampleFreq) #wait
displayData() #show in terminal
#count = count+1
#print(count)
Maybe someone already solved this problem or can give me an alternative to sqlite3 which works with flask.
Suggestion: add a more complete exception handling routine, because your stacktrace could be more verbose.
But judging from your trace the offending line #45 could be this: conn.commit() (or the line above). Python is already helping you pinpoint the error. There is something wrong in function logData.
Could it be that you are feeding incorrect data to your table BME280_data ? To debug your application I would strongly recommend that you print log the data you are trying to insert (use the logging module to output to file and/or console). I don't know the structure of your table but some of your fields could have a definition (data type) that is not compatible with the data you are trying to insert. The fact that you are able to predictably reproduce the problem is quite telling and my hunch is that the data could be the cause.
To sum up: take good habits now and add at least basic exception handling.
A quality application should have exception handling and log errors so they can be reviewed and remediated by a human. This is even more important for unattended applications, because you are not in front of the console and you may not even have a chance to see problems that occur.
Here is one tutorial that may help: https://code.tutsplus.com/tutorials/error-handling-logging-in-python--cms-27932

I import the libraries and I defined the function for get the path of my file mp3, but when I run librosa.load I have this error

Import libraries
import librosa
import librosa.display
Defined function
def get_audio_path(audio_dir, track_id):
tid_str = '{:06d}'.format(track_id)
return os.path.join(audio_dir, tid_str[:3], tid_str + '.mp3')
Plot single spectogram
filename = get_audio_path(AUDIO_DIR, 36096)
y, sr = librosa.load(filename)
print(len(y),sr)
RuntimeError: Error opening '/home/ub10/Project 1/fma_small/036/036096.mp3': File contains data in an unknown format.
Please any solution for this issue or a different method !
Use newest version of librosa. This should fix problem.

Redirect logs to file in Pybel?

Similar to this post, but rather than change the logging level, I would like to redirect all logging information to a file. I believe the relevant API call is:
pybel.ob.obErrorLog.SetOutputStream()
or:
pybel.ob.OBMessageHandler().SetOutputStream()
But the SetOutputStream() method only accepts objects of type std::ostream *, not Python file streams, e.g. open('/path/to/log.txt', 'w') or sys.stdout.
Here are a few things I tried:
from openbabel import openbabel
import io
import sys
obHandler = openbabel.OBMessageHandler()
obHandler.SetOutputStream(io.BytesIO())
##Out: TypeError: in method 'OBMessageHandler_SetOutputStream', argument 2 of type 'std::ostream *'
obHandler.SetOutputStream(sys.stderr)
##Out: TypeError: in method 'OBMessageHandler_SetOutputStream', argument 2 of type 'std::ostream *'
with open("test.out", "w") as fd:
obHandler.SetOutputStream(fd)
##Out: TypeError: in method 'OBMessageHandler_SetOutputStream', argument 2 of type 'std::ostream *'
TL;DR: is there a reasonable way to direct log information to a file in PyBel?
One way work around this error is to capture the standard error stream.
Unfortunately one cannot directly redirect the standard error to an IOStream, as OpenBabel is operating on the underlying C standard error and unaware of the Python one.
But, thanks to this Stack Overflow answer, it is actually possible to capture the underlying error stream to a string.
With the OutputGrabber class loaded/imported, you can capture the output as so:
import sys
from openbabel import openbabel
obConversion = openbabel.OBConversion()
obConversion.SetInFormat("sdf")
mol = openbabel.OBMol()
out = OutputGrabber(sys.stderr)
with out:
success = obConversion.ReadString(mol, "INVALID\n\n")
And the text is now in out.capturedtext:
print(out.capturedtext)
==============================
*** Open Babel Warning in ReadMolecule
WARNING: Problems reading a MDL file
Cannot read comment line

TypeError: initial_value must be str or None, not _io.BytesIO

haii everyone...
i have one module in odoo8 version its contain Import the products and quantity in inventory adjustment in that read the file code is there
import cStringIO
data = base64.b64decode(self.data)
self.data contain the file path..
file_input = cStringIO.StringIO(data)
it is working fine in odoo8.
I want to implement this module in odoo11
in odoo python version is changes that' way it does not know about the cStringIO. it knows only StringIO
from io import StringIO
import io
data = base64.b64decode(self.data)
file_input = io.StringIO(data)
raise error
TypeError: initial_value must be str or None, not bytes
i changes the code above lines
but it does not take the data. because it is return bytes form, here it want string
then next i had use
file_input = io.BytesIO(data) -->this
raise the error
TypeError: initial_value must be str or None, not bytes
please any one help me to rectify this ...
Thanks in advance..
replace this:
data = base64.b64decode(self.data)
to:
data = base64.b64decode(self.data).decode('utf-8')

Resources