Python Error Handling while base decoding - python-3.x

I tried to do the following :
I have read a code in base64 via QR Code and then I converted it.
If I get an error while I do the convert, I will write a error variable to 1 and then continue without exiting the program.
I don't find a solution for me. Did anyone has an idea how I can handle it?
I tried it with the Python Try Command but I didn't get it working or I have done something wrong.
here is a snip of my code:
secure = base64.b64decode(secure_base).decode("utf-8", "ignore")
number = base64.b64decode(number_base).decode("utf-8", "ignore")
start = int(base64.b64decode(start_base).decode("utf-8", "ignore"))
end = int(base64.b64decode(end_base).decode("utf-8", "ignore"))
thanks a lot.

You can use the try and Except in python in the following manner.
try:
"""some intelligent program here, which some times may FOOBAR"""
except Exception as e:
error_recieved = e
"""Do whatever you want here incase of an error"""
Remember that the program in try skips to except just after the line in which the error/exception occured.

Related

Except python does not catch Windows error FileNotFoundError | "The system cannot find the specified path." [duplicate]

I have this python code:
import os
try:
os.system('wrongcommand')
except:
print("command does not work")
The code prints:
wrongcommand: command not found
Instead of command does not work. Does anyone know why it's not printing my error message?
If you want to have an exception thrown when the command doesn't exist, you should use subprocess:
import subprocess
try:
subprocess.run(['wrongcommand'], check = True)
except subprocess.CalledProcessError:
print ('wrongcommand does not exist')
Come to think of it, you should probably use subprocess instead of os.system anyway ...
Because os.system() indicates a failure through the exit code of the method
return value == 0 -> everything ok
return value != 0 -> some error
The exit code of the called command is directly passed back to Python.
There is documentation telling you that os.system() would raise an exeption in case of a failure. os.system() just calls the underlaying system() call of the OS and returns its return value.
Please read the os.system() documentation carefully.
Although subprocess might be your best friend. os.system is still useful in somewhere, especially to the programmer play C/C++ mode.
Hence, the code will be below.
import os
try:
os_cmd = 'wrongcommand'
if os.system(os_cmd) != 0:
raise Exception('wrongcommand does not exist')
except:
print("command does not work")
There are two problems in your code snippet. First of all, never just do try: ... except:, always be specific about which exception you want to handle. Otherwise, your program simply swallows any kind of error, also those that you do not expect. In most cases, this will lead to unexpected behavior at some other point during runtime.
Furthermore, os.system() calls should most of the time be replaced by their counterparts from the subprocess module.
To see what goes wrong, leave out the try/except block and actually look at the traceback/exception. As others have pointed out, you will notice that there is no exception in your case which is why your custom string is not printed.
Bottom line: think about which specific exceptions can occur in your code block. Think hard about which of them you expect to happen for certain reasons and handle those appropriately. Do not handle those that you do not expect.
wrongcommand: command not found is the output of the shell os.system is using to invoke the command. os.system did not throw an exception
EDIT: edited by copy-and-pasting part of mgilson's comment
There is one more easiest ways is:
import os
def dat():
if os.system('date') == 0:
print("Command successfully executed")
else:
print("Command failed to execute")
dat()

Check for compilation error in Excel via COM

I am connected to an Excel application and can execute the "Debug"->"Compile VBAProject" from my Python code using win32com like so (inspired by code from here):
from win32com import client
def compile(self):
self.__excel = client.GetActiveObject("Excel.Application")
compile_button = self.__excel.VBE.CommandBars.FindControl(1, 578)
compile_button.Execute()
If there is a compilation error in the Excel VBA code I get a popup message in Excel telling me the error just fine.
Now I would like to check from the Python code if there was a compilation error and raise an exception if there was. I don't necessarily need the compilation error to be part of the exception but if that were possible I would of course gladly take that, too.
Can this be done somehow?
I've been experimenting with all kinds of window counts before and after the compilation etc. but so far have not found a property of any object that would indicate that there was a popup or a compilation error.
Ok, I found a somewhat ugly but doable way - that I would like to document for others having the same issue:
You need to import a code file into the opened Excel file that has (at least) one function defined. Then you can call this function from your Python code and catch any exception. If there was an exception your code - including the imported file - did not compile, if there is none the compilation was pass.
Here's my code:
compile_code.bas
Public Sub compileCode()
' doesn't need to do anything, it just needs to be available!
End Sub
Python file
from win32com import client
def compile(self) -> bool:
self.__excel = client.GetActiveObject("Excel.Application")
self.__book = self.__excel.ActiveWorkbook
self.__book.VBProject.VBComponents.Import(<Path_to_compile_code.bas>)
try:
self.__excel.Application.Run("compileCode")
# if you reach here the code compiled
return True
except Exception:
return False

Syntax Error on Get function in requests module

My code throws up syntax error on trying to download data from NYSE site get request functions.
I have changed the format of url string yet the error reappeared.
def get_decade(start=1920, end=1929, extension='prn'):
try:
link = requests.get(f"https://www.nyse.com/publicdocs/nyse/data/Daily_Share_Volume_{start}-{end}.{extension}")
file = os.path.join("..","Data", f"Daily_Share_Volume_{start}-{end}.{extension}")
if link.status_code ==404:
raise
else:
with open(file, "w") as temp_file:
temp_file.write(str(link.content.decode("utf-8")))
print(f"Successfully downloaded {start}-{end}")
except:
print("There was an issue with the download. \n\
You may need a different date range or file extension. \n\
Check out https://www.nyse.com/data/transactions-statistics-data-library")
The error message upon calling the function.
link = requests.get(f"https://www.nyse.com/publicdocs/nyse/data/Daily_Share_Volume_{start}-{end}.{extension}")
^
SyntaxError: invalid syntax
Resolution that will clear the invalid syntax error.
Source
As of Python 3.6, f-strings are a great new way to format strings.
You stated in a comment that
I know how to retrieve the file. I 'm using Python 3.5
In other words, upgrade your Python version or don't use f-strings.

Is there an option to return after occuring error to the outest loop by try-except?

I have the task to measure the time between two versions of code, after running it hundred times. The programm actual interrupts at a point. It is someone else's task to fix it. So what I already did is, I called the programm from another script in a for loop. But after the occuring error (FileNotFoundError), I didn't find a way to return to the outest loop, yet, to let it run once again.
I already put before the point, where the error occurs, a try part, but I don't know what to put in the except part. Sure, I can put everywhere, in each used function, a "return" to end up in the outest loop. Is there a way much simplier than that?
with open('bla-program.py') as f:
script = f.read()
z = np.arange(0, 100, 1)
a = time.time()
for i in z:
exec(script) ### now, that's the point, I cannot reach again
b=time.time()
print(a, b, "difference", b-a)
\now calling various functions, calculating some stuff, ... follows, landing in another file directed by bla-program, where error is occuring, is displayed below
try:
os.mkdir(os.path.join(bla.blabla, "bladibla.org"))
except FileNotFoundError:
return ###on this point, I want to return to the point displayed above
Instead of the termination of run by the FileNotFoundError, I want to run the program hundred times to the point of error.
You should put try/except around exec(script):
for i in z:
try:
exec(script)
except:
# Print an error message or whatever

audio file isn't being parsed with Google Speech

This question is a followup to a previous question.
The snippet of code below almost works...it runs without error yet gives back a None value for results_list. This means it is accessing the file (I think) but just can't extract anything from it.
I have a file, sample.wav, living publicly here: https://storage.googleapis.com/speech_proj_files/sample.wav
I am trying to access it by specifying source_uri='gs://speech_proj_files/sample.wav'.
I don't understand why this isn't working. I don't think it's a permissions problem. My session is instantiated fine. The code chugs for a second, yet always comes up with no result. How can I debug this?? Any advice is much appreciated.
from google.cloud import speech
speech_client = speech.Client()
audio_sample = speech_client.sample(
content=None,
source_uri='gs://speech_proj_files/sample.wav',
encoding='LINEAR16',
sample_rate_hertz= 44100)
results_list = audio_sample.async_recognize(language_code='en-US')
Ah, that's my fault from the last question. That's the async_recognize command, not the sync_recognize command.
That library has three recognize commands. sync_recognize reads the whole file and returns the results. That's probably the one you want. Remove the letter "a" and try again.
Here's an example Python program that does this: https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/cloud-client/transcribe.py
FYI, here's a summary of the other types:
async_recognize starts a long-running, server-side operation to translate the whole file. You can make further calls to the server to see whether it's finished with the operation.poll() method and, when complete, can get the results via operation.results.
The third type is streaming_recognize, which sends you results continually as they are processed. This can be useful for long files where you want some results immediately, or if you're continuously uploading live audio.
I finally got something to work:
import time
from google.cloud import speech
speech_client = speech.Client()
sample = speech_client.sample(
content = None
, 'gs://speech_proj_files/sample.wav'
, encoding='LINEAR16'
, sample_rate= 44100
, 'languageCode': 'en-US'
)
retry_count = 100
operation = sample.async_recognize(language_code='en-US')
while retry_count > 0 and not operation.complete:
retry_count -= 1
time.sleep(10)
operation.poll() # API call
print(operation.complete)
print(operation.results[0].transcript)
print(operation.results[0].confidence)
for op in operation.results:
print op.transcript
Then something like
for op in operation.results:
print op.transcript

Resources