python 3 EOFError: EOF when reading a line - python-3.x

The errors saying
Traceback (most recent call last):
File "rental_car-customer-data-2.py", line 18, in
odoEnd = int(input("Ending Odometer Reading:"))
EOFError: EOF when reading a line
I have tried removing int and copy paste same line from above that doesn't error odoStart and change it to odoEnd but not working??
not sure if the odoEnd - odoStart will work either?
odoStart = int(input ("Starting Odometer Reading:"))
odoEnd = int(input("Ending Odometer Reading:"))****
print(odoStart)
print(odoEnd)
totalMiles = (odoEnd - odoStart)
print (totalMiles)

This is a common error when reading a file. When you get to the end of a file when reading in python you have to go back to line one by using this command: file.seek(0), where file is the name of the file variable.

Related

Cannot use custom key words with pvporcupine

I have already created an account in picovoice and recieved an access key, but when I try to put the path of my ppn file, it shows an error:
`
[ERROR] loading keyword file at 'C:\Users\Priyam\Desktop\hey keyazip' failed with 'IO_ERROR'
Traceback (most recent call last):
File "e:\Personal Project\import struct.py", line 13, in <module>
porcupine = pvporcupine.create(access_key='access key',
File "C:\Users\Priyam\AppData\Roaming\Python\Python310\site-packages\pvporcupine\__init__.py", line 77, in create
return Porcupine(
File "C:\Users\Priyam\AppData\Roaming\Python\Python310\site-packages\pvporcupine\porcupine.py", line 158, in __init__
raise self._PICOVOICE_STATUS_TO_EXCEPTION[status]()
pvporcupine.porcupine.PorcupineIOError
the code is:
`
porcupine=None
paud=None
audio_stream=None
try:
access_key="access key"
porcupine = pvporcupine.create(access_key='access key',
keyword_paths=['C:\\Users\Priyam\Desktop\hey keyazip'],keywords=['hey keya']) #pvporcupine.KEYWORDS for all keywords
paud=pyaudio.PyAudio()
audio_stream=paud.open(rate=porcupine.sample_rate,channels=1,format=pyaudio.paInt16,input=True,frames_per_buffer=porcupine.frame_length)
while True:
keyword=audio_stream.read(porcupine.frame_length)
keyword=struct.unpack_from("h"*porcupine.frame_length,keyword)
keyword_index=porcupine.process(keyword)
if keyword_index>=0:
print("hotword detected")
finally:
if porcupine is not None:
porcupine.delete()
if audio_stream is not None:
audio_stream.close()
if paud is not None:
paud.terminate()
`
I tried the code above and the code provided by picovoice itself, yet I am facing the same issues
It looks like Porcupine is having trouble finding your keyword file: [ERROR] loading keyword file at 'C:\Users\Priyam\Desktop\hey keyazip' failed with 'IO_ERROR'.
The Picovoice console provides the keyword inside a compressed .zip file. You will need to decompress the file and in your code update the path to lead to the .ppn file located inside. For example: C:\\Users\Priyam\Desktop\hey-keya_en_windows_v2_1_0\hey-keya_en_windows_v2_1_0.ppn

How to use bulk_load in apache airflow

I have apache airflow 2.1.4 and postgres database.
I need to insert multiple rows at a time. So I am going to use bulk_load method of PostgresHook but get error everytime.
data = pd.read_csv(open(filepath, 'rb'))
buffer = StringIO()
buffer.write(data.to_csv(index=None, header=None, sep='\t'))
buffer.seek(0)
schema_table = 'schema.table'
with PostgresHook(postgres_conn_id='my_pg_database'):
PostgresHook.bulk_load(table=schema_table, tmp_file=buffer)
The error I get:
Traceback (most recent call last):
File "/home/airflow/dags/my_python_file.py", line 76, in <module>
my_func(filepath=my_file, target_schema=schema, target_table=table)
File "/home/airflow/dags/my_python_file.py", line 39, in my_func
with PostgresHook(postgres_conn_id='my_pg_database'):
AttributeError: __enter__
I couldn't even find some examples of bulk_load usage. Would appriciate any clue. Thank you.
Postgres Hook (and any other hooks really) are not "context managers". You cannot use with: to use them.
Something like that should work:
postgres_hook = PostgresHook(postgres_conn_id='my_pg_database')
postgres_hook.bulk_load(...)

Python image save error - raise ValueError("unknown file extension: {}".format(ext)) from e ValueError: unknown file extension:

Am just having four weeks of experience in Python. Creating a tool using Tkinter to paste a new company logo on top of the existing images.
The Below method is to, get all images in the given directory and paste the new logo on the initial level. Existing image, edited image, x-position, y-position, a preview of the image and few data's are store in global instance self.images_all_arr.
def get_img_copy(self):
self.images_all_arr = []
existing_img_fldr = self.input_frame.input_frame_data['existing_img_folder']
for file in os.listdir(existing_img_fldr):
img_old = Image.open(os.path.join(existing_img_fldr, file))
img_new_copy = img_old.copy()
self.pasteImage(img_new_copy, initpaste=True) #process to paste new logo.
view_new_img = ImageTk.PhotoImage(img_new_copy)
fname, fext = file.split('.')
formObj = {
"fname": fname,
"fext": fext,
"img_old": img_old,
"img_new": img_new_copy,
"img_new_view": view_new_img,
"add_logo": 1,
"is_default": 1,
"is_opacityImg": 0,
"pos_x": self.defult_x.get(),
"pos_y": self.defult_y.get()
}
self.images_all_arr.append(formObj)
After previewing each image in Tkinter screen, doing some adjustment in position x and y(updating pos_x and pos_y in the list self.images_all_arr) depends upon the necessity.
Well, once all done. Need to save the edited images. Below method to save images, iterating the list self.images_all_arr and call save method as img['img_new'].save(dir_output) since img['img_new'] has updated image.
def generate_imgae(self):
if len(self.images_all_arr):
dir_output = 'xxxxx'
for img in self.images_all_arr:
print(img['img_new'])
img['img_new'].save(dir_output)
print('completed..')
But it returns below error,
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files (x86)\Python38-32\lib\site-packages\PIL\Image.py", line 2138, in save
format = EXTENSION[ext]
KeyError: ''
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python38-32\lib\tkinter_init_.py", line 1883, in call
return self.func(*args)
File "C:\Users\662828\WORKSPACE\AAA_python_projects\AMI_automation_poc2\position_and_images.py", line 241, in generate_imgae
img['img_new'].save(dir_output)
File "C:\Program Files (x86)\Python38-32\lib\site-packages\PIL\Image.py", line 2140, in save
raise ValueError("unknown file extension: {}".format(ext)) from e
ValueError: unknown file extension:
dir_output doesn't contain the file extension, its just xxxxx. You need to specify what image file format you want. the error tells us this by saying "unknown file format".
Basically, you either need to include the extension in the file name, or pass it as the next parameter in image.save. You can check out the documentation here
eg.
image.save('image.png')
or
image.save('image', 'png')
The below code solved my issue. By giving the exact directory, filename and extension of the image as param to the method image.save(). Here the result of opfile is, C:\Users\WORKSPACE\AAA_python_projects\test\valid.png.
def generate_imgae(self):
if len(self.images_all_arr):
dir_output = r"C:\Users\WORKSPACE\AAA_python_projects\test"
if not os.path.isdir(dir_output):
os.mkdir(dir_output)
for img in self.images_all_arr:
opfile = os.path.join(dir_output, '{}.{}'.format(img['fname'], img['fext'] ))
img['img_new'].save(opfile)
print('completed..')
Thanks #dantechguy

Print traceback "ending" on the assert-line, in Python3 unittest addFailure

I have made a simple, custom TestResult class (not inheriting from anything). When my python unittest fails, addFailure(self, test, err) is called as expected.
err[2] contains a traceback
I now print the traceback with this command: traceback.print_tb(err[2])
The print out contains two more levels than expected/desired.
File "/usr/lib64/python3.4/unittest/case.py", line 58, in testPartExecutor
yield
File "/usr/lib64/python3.4/unittest/case.py", line 580, in run
testMethod()
File "/home/xplatformer/code/tools/python/exception_test/my_test.py", line 23, in test_my4
self.assertEqual(5,4)
File "/usr/lib64/python3.4/unittest/case.py", line 800, in assertEqual
assertion_func(first, second, msg=msg)
File "/usr/lib64/python3.4/unittest/case.py", line 793, in _baseAssertEqual
raise self.failureException(msg)
How can I get the traceback to "end" at the assertEqual (line 23 in my_test.py)
Similarly, when extracting the filename like this: err[2].tb_frame.f_code.co_filename, I get case.py and not my_test.py as expected/desired.
How can I get the filename where the assertion occurred?
from the log it is pretty clear that, there is self.assertEqual(5,4) which fails the test case on line 23 in the method test_my4 in file /home/xplatformer/code/tools/python/exception_test/my_test.py
change the self.assertEqual(5,5) will pass the test case.

Sublime Text - Add a header

I found this: https://github.com/kigiri/sublime-header-42
I put on packages folder but when I'm doing ctrl+shift+h, The header doesn't appear.
How can I resolve this?
(My OS: W8)
I believe it's not compatible with Windows out of the box, when I try to install it I have this error in Sublime's console:
Traceback (most recent call last):
File "C:\Program Files\Sublime Text 3\sublime_plugin.py", line 550, in run_
return self.run(edit, **args)
File "C:\Users\Thibaut\AppData\Roaming\Sublime Text 3\Packages\sublime-header-42-master\Header.py", line 142, in run
self.view.replace(edit, line, self.generate(project))
File "C:\Users\Thibaut\AppData\Roaming\Sublime Text 3\Packages\sublime-header-42-master\Header.py", line 109, in generate
created = "Created: " + self.get_date() + " " + self.get_user()
File "C:\Users\Thibaut\AppData\Roaming\Sublime Text 3\Packages\sublime-header-42-master\Header.py", line 82, in get_user
return os.environ['USER']
File "./os.py", line 676, in __getitem__
KeyError: 'USER'
There is no USER environment variable on Windows 8+, so you'll probably need to update the script a bit if you want to use it. Simply replacing os.environ['USER'] with os.environ['USERNAME'] works fine though.

Resources