I am writing python code to install all the library packages required by my program in the linux environment.So the linux may contain python 2.7 or 2.6 or both so I have developed a try and except block codes that will install pip packages in linux. Try block code consists of python 2.7 version pip install and Catch block contains python 2.6 version pip install. My Problem is the peace of code is working fine, when i tried to install pandas in python 2.6 its getting me some errror. I want to catch that exception. Can you please tell me how to improve my try except blocks to catch that exception
required_libraries = ['pytz','requests','pandas']
try:
from subprocess import check_output
pip27_path = subprocess.check_output(['sudo','find','/','-name','pip2.7'])
lib_installs = [subprocess.call((['sudo',pip27_path.replace('\n',''),'install', i])) for i in required_libraries]
except:
p = subprocess.Popen(['sudo','find','/','-name','pip2.6'], stdout=subprocess.PIPE);pip26_path, err = p.communicate()
lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]
You can catch several exceptions using one block. Let's use Exception and ArithmeticError for exceptions.
try:
# Do something
print(q)
# Catch exceptions
except (Exception, ArithmeticError) as e:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(e).__name__, e.args)
print (message)
If you need to catch several exceptions and handle each one on its own then you'd write an except statement for each one.
try:
# Do something
print(q)
# Catch exceptions
except Exception as e:
print (1)
except ArithmeticError as e:
print (2)
# Code to be executed if the try clause succeeded with no errors or no return/continue/break statement
else:
print (3)
You can also check if the exception is of type "MyCustomException" for example using if statements.
if isinstance(e, MyCustomException):
# Do something
print(1)
As for your problem, I suggest splitting the code into two functions.
install(required_libraries)
def install(required_libraries, version='pip2.7'):
# Perform installation
try:
from subprocess import check_output
pip27_path = subprocess.check_output(['sudo','find','/','-name', version])
lib_installs = [subprocess.call((['sudo',pip27_path.replace('\n',''),'install', i])) for i in required_libraries]
except Exception as e:
backup(required_libraries)
def backup(required_libraries, version='pip2.6'):
try:
p = subprocess.Popen(['sudo','find','/','-name',version]], stdout=subprocess.PIPE);pip26_path, err = p.communicate()
lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]
except Exception as e:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(e).__name__, e.args)
print (message)
#Handle exception
Note: I didn't test this, I'm no expert as well so I hope I can help.
Useful links:
Built-in Exceptions
Errors and Exceptions
Compound statements
Related
Running some code with Python3 reports the below error:
$ python3 report.py --regions ap-southeast-2 --file file.csv
File "report.py", line 51
except Exception, e:
^
SyntaxError: invalid syntax
Research indicates that this deprecated syntax. I have found conflicting information on how I may fix this.
I have tried to engage python3 syntax, which I believe would be to switch
try:
f = file(filepath, 'wt')
except Exception, e:
f = None
sys.stderr.write ('Could not open file %s. reason: %s\n' % (filepath, e))
To:
try:
f = file(filepath, 'wt')
except:
f = None
sys.stderr.write ('Could not open file %s. reason: %s\n' % (filepath, e))
What happens then is that I get errors relating to the "e" being missing... so I'm unsure how best and easiest to resolve the syntax issues between the two versions. Can you help or advise? Thanks!
If you really want a method that is compatible for both Python2 and Python3,
Then try something like this:
import sys
try:
### your filepath code goes here or any other code
except Exception:
tb, err = sys.exc_info()[:2]
print(err)
Using exc_info() here is good as it provides you with a tuple of information on what the error and the traceback to that faulting code, specifically the (type, value, traceback). In this case, you are getting back the traceback and the error (value).
I need to periodically update Online Excel file on SharePoint. The problem occures when this file is opened by user. In this case I am getting Windows error message as below:
Is it possible to handle such error in Python script? By handle I mean keep trying to save file after some time by using time.sleep function. I have tried with most common approach:
import shutil
try:
shutil.copy2('Track_Changes_Testing.xlsx', destination_on_sharepoint)
except Exception as err:
print(err)
But I only get Windows error message popping out
You could do this with time.sleep() and a while loop, like you requested. However be aware that this script will run forever if the file does continue to be used. I am not sure if that behavior is intended or would be ideal
import shutil
import time
import sys
while True:
print("Runned") #debugging
try:
shutil.copy2('Track_Changes_Testing.xlsx', destination_on_sharepoint)
break
except (OSError, IOError):
print("OSError or IOError")
# wair 5 min before trying again
time.sleep(300)
except shutil.Error as e:
print(f"Error while copying: {e}" )
# wair 5 min before trying again
time.sleep(300)
except:
print("Unexpected error:", sys.exc_info()[0])
# wair 5 min before trying again
time.sleep(300)
import config as regex
except Exception as e:
logging.error('Issue in Calcutaing: '+str(e))
return None
I want to execute this program but it gives the following error.
import config as regex
File "/usr/local/lib/python3.5/dist-packages/config.py", line 733
except Exception, e:
^
In Python 3 the line
except Exception, e:
must be written as
except Exception as e:
Likely, if you want your module to be published, you should also give it a more descriptive name than config.
I am using the below code for downloading files from a ftp server.But I am getting an error [Errno 2] No such file or directory:, but the file present in the server and I can able download it via terminal. Can anyone help me!!
import ftplib
import os
remotpath='folder/subfolder'
try:
ftpclient = ftplib.FTP('ftp.xxxx.com')
ftpclient.login('user', 'pass')
ftpclient.cwd(remotpath)
print "login succeessfull"
files = ftpclient.nlst()
for eachFile in files:
saveTo = os.path.join(remotpath,eachFile)
if (not os.path.exists(saveTo)):
try:
ftpclient.retrbinary('RETR ' + eachFile, open(saveTo, 'wb').write)
#logging.info('\tdownloaded ' + saveTo)
downloaded += 1
except BaseException as e:
print('\terror downloading inside first %s - %s' % (eachFile, e.__str__()))
except ftplib.error_perm:
print('\terror downloading inside second %s - %s' % (eachFile, ftplib.error_perm))
except Exception as e:
print e
Does the destination directory ./folder/subfolder exist?
If not you need to create it before downloading files. Either do so using your OS commands (mkdir), or in Python using os.makedirs() :
import os
try:
os.makedirs(remotpath)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
You can add it somewhere before the for loop.
On another issue, the order of you exception handlers means that all exceptions raised in the inner try block would be handled in the except BaseException statement. This means that ftplib.error_perm will be caught in that statement because BaseException is more general, and not in the ftplib.error_perm statement as you might expect.
You should reorder your except statements in order of increasing generality.
Help me figure out how the script will keep on running when WMI can't connect to host and go to next computer in list. Should I use continue after except?
import wmi
MachineList = ["Computer1","Computer2","Computer3"]
try:
for machines in MachineList:
c = wmi.WMI(machines) # <---- Go to next in the for loop when connection fail???
for os in c.Win32_OperatingSystem():
print os.Caption
except:
pass
import wmi
MachineList = ["Computer1","Computer2","Computer3"]
for machines in MachineList:
try:
c = wmi.WMI(machines) # <---- Go to next in the for loop when connection fail???
for os in c.Win32_OperatingSystem():
print os.Caption
except Exception: #Intended Exception should be mentioned here
print "Cannot Connect to {}".format(machines)
Generally speaking unless you are using exception for control flow, it should be caught as soon as plausible to prevent mixing with other exceptions. Also you should be specific what exception you want to catch rather than catching something generic.
for machine in MachineList:
try:
c = wmi.WMI(machine)
for os in c.Win32_OperatingSystem():
print os.caption
except Exception:
print "Failed on machine %s" % machine