Hi I write a simple python code it will check folder/dir is exist or not in the /usr/share/* file but it's fail to check
import os
try:
os.path.isdir('/usr/share/sqlmap')
print 'sqlmap found'
except OSError:
print "Sqlmap not found"
#Output
sqlmap found
Although it's not exist in my that directory. Please anyone tell me where my mistake is.
The documentation isn't very clear about this, but isdir would return False if the directory doesn't exist. It wouldn't throw an exception. Therefore it would be more appropriate for you to use an if-else block in this case.
For example:
import os
if os.path.isdir('/usr/share/sqlmap'):
print 'sqlmap found'
else:
print "Sqlmap not found"
Why do you expect an error to be thrown, use:
import os
if os.path.isdir('/usr/share/sqlmap'):
print 'sqlmap found'
else:
print "Sqlmap not found"
Related
This question already has answers here:
python sys.exit not working in try [duplicate]
(2 answers)
Closed 4 years ago.
I have a small python script which I have written specifically for this question.
#!/usr/bin/python3
import sys
def testfunc(test):
if test == 1:
print("test is 1")
else:
print("test is not 1")
sys.exit(0)
try:
testfunc(2)
except:
print("something went wrong")
print("if test is not 1 it should not print this")
What I was expecting is that when test = 2 the script should exit. Instead what I get is this;
test is not 1
something went wrong
if test is not 1 it should not print this
I am new to python but not to scripting/coding. I have searched all over the place and every answer is simply "use sys.exit()"
Well it seems that sys.exit() has what seems to be unexpected behaviour when it is contained within try/except. If I remove the try it behaves as expected
Is this normal behaviour? If so is there a way to hard exit the script with out it continuing to execute into the exception block when test = 2?
Note: this is sample code that is a simplified version of the logic I am intending to use in another script. The reason the try/except is there is because testfunc() will be called using a variable and I want to catch the exception if an invalid function name is provided
Thanks in advance
Edit: I have also tried quit(), exit(), os._exit() and raise SystemExit
Here, sys.exit(0) raises a SystemExit exception.
Since you put the calling code inside a Try-Except block, it's as expected caught. If you want to propagate the exception, recall a sys.exit() with the code status:
try:
testfunc(2)
except SystemExit as exc:
sys.exit(exc.code) # reperform an exit with the status code
except:
print("something went wrong")
print("if test is not 1 it should not print this")
I'm trying to print a text a text file from a webserver in a python program but I am receiving errors. Any help would be greatly appreciated, here is my code:
import RPi.GPIO as GPIO
import urllib2
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5,GPIO.OUT)
true = 1
while(true):
try:
response = urllib2.urlopen('http://148.251.158.132/k.txt')
status = response.read()
except urllib2.HTTPError, e:
print e.code
except urllib2.URLError, e:
print e.args
print status
if status=='bulbion':
GPIO.output(5,True)
elif status=='bulbioff':
GPIO.output(5,False)
By your comments, it appears your error: "SyntaxError: Missing parentheses in call to print", is caused by excluding parentheses/brackets in your print statements. People usually experience these errors after they update their python version, as the old print statements never required parentheses. The other error: "SyntaxError: unindent does not match any outer indentation level", is because your print statement on line 16 is one space behind all of your other statements on that indentation level, you can fix this problem by moving the print statement one space forward.
Changing your code to this should fix the problems:
import RPi.GPIO as GPIO
import urllib2
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5,GPIO.OUT)
true = 1
while(true):
try:
response = urllib2.urlopen('http://148.251.158.132/k.txt')
status = response.read()
except urllib2.HTTPError, e:
print (e.code)
except urllib2.URLError, e:
print (e.args)
print (status)
if status=='bulbion':
GPIO.output(5,True)
elif status=='bulbioff':
GPIO.output(5,False)
Hope this helps!
I just wrote a simple webscraping script to give me all the episode links on a particular site's page. The script was working fine, but, now it's broke. I didn't change anything.
Try this URL (For scraping ) :- http://www.crunchyroll.com/tabi-machi-late-show
Now, the script works mid-way and gives me an error stating, ' Element not found in the cache - perhaps the page has changed since it was looked up'
I looked it up on internet and people said about using the 'implicit wait' command at certain places. I did that, still no luck.
UPDATE : I tried this script in a demote desktop and it's working there without any problems.
Here's my script :-
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
import time
from subprocess import Popen
#------------------------------------------------
try:
Link = raw_input("Please enter your Link : ")
if not Link:
raise ValueError('Please Enter A Link To The Anime Page. This Application Will now Exit in 5 Seconds.')
except ValueError as e:
print(e)
time.sleep(5)
exit()
print 'Analyzing the Page. Hold on a minute.'
driver = webdriver.Firefox()
driver.get(Link)
assert "Crunchyroll" in driver.title
driver.implicitly_wait(5) # <-- I tried removing this lines as well. No luck.
elem = driver.find_elements_by_xpath("//*[#href]")
driver.implicitly_wait(10) # <-- I tried removing this lines as well. No luck.
text_file = open("BatchLink.txt", "w")
print 'Fetching The Links, please wait.'
for elem in elem:
x = elem.get_attribute("href")
#print x
text_file.write(x+'\n')
print 'Links have been fetched. Just doing the final cleaning now.'
text_file.close()
CleanFile = open("queue.txt", "w")
with open('BatchLink.txt') as f:
mylist = f.read().splitlines()
#print mylist
with open('BatchLink.txt', 'r') as inF:
for line in inF:
if 'episode' in line:
CleanFile.write(line)
print 'Please Check the file named queue.txt'
CleanFile.close()
os.remove('BatchLink.txt')
driver.close()
Here's a screenshot of the error (might be of some help) :
http://i.imgur.com/SaANlsg.png
Ok i didn't work with python but know the problem
you have variable that you init -> elem = driver.find_elements_by_xpath("//*[#href]")
after that you doing some things with it in loop
before you finishing the loop try to init this variable again
elem = driver.find_elements_by_xpath("//*[#href]")
The thing is that the DOM is changes and you loosing the element collection.
So I am trying to set up a small script in Python's IDLE. The IDLE syntax check tells me this code has a syntax error:
from ftplib import FTP
import os
def ftpconnect(address, username, password):
ftp_connection = 0
ftp = FTP(address)
try:
ftp.login(username, password)
print(ftp.getwelcome())
if ftp.getwelcome() == '220 FTP Connected!':
return 1
else:
return 0
print(ftpconnect('10.10.10.xxx', 'xxx', 'xxx'))
The syntax error comes anywhere that I try to get out of the "try" statement, here being the "else:" line. I've looked around and it seems like I have the right syntax...any thoughts?
Thanks! I'm running Python 2, not 3.
In addition to the problem with my syntax (missing except statement entirely), my ftp attempt statement was outside of the try block. Since I was not "try"ing it, it failed anyway.
I am reading python tutorial here and there is one thing that I can't quite make sense out of. From the docs:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
From the explanation in the doc:
The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.
My question is it how does it protect against accidentally catching an exception that wasn't raised in this try block. I don't see what they mean. Can anyone give an example?
One possible alternative approach that you might try is this:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
print arg, 'has', len(f.readlines()), 'lines'
f.close()
except IOError:
print 'cannot open', arg
Here if there is an exception during f.readlines() or f.close() then it will be caught by the except block and you will get the error message 'cannot open' which is wrong.