This question already has answers here:
Manually raising (throwing) an exception in Python
(11 answers)
Closed 6 years ago.
I want to create an error message in Python, i.e. the program should be interrupted and an (if possible coloured) error message should be printed. For instance:
If a == 0:
Error("a should be nonzero")
In Matlab, you can do this using the error instruction. How can you do this in Python? I have found this page but I am not sure that is what I am looking for.
You can raise it like so:
if a == 0:
raise ValueError("a should be nonzero")
or simply by using assert as:
assert a!=0, "a should be nonzero!"
Related
This question already has answers here:
Store output of subprocess.Popen call in a string [duplicate]
(15 answers)
Closed 1 year ago.
So recently I've been working on automating my code for bug bountys but i want to have a overall out put so it shows what it got neatly
(xssstrike is for example here)
website = (input(Fore.GREEN + "enter url/website for this scan: "))
ops = (input(Fore.GREEN + "enter other operators for xxstrike here (with spaces): "))
def xssstrike():
try:
os.chdir("/mnt/usb/xss-strike")
os.system(f"python3 xsstrike.py {ops} -u {website}")
except ValueError:
raise print("oops! there was an error with xss strike!")
i want to put the output from os.system(f"python3 xsstrike.py {ops} -u {website}") into a variable so i can print it later at the end of the code such as
print("<><><> xss strike output results <><><>")
print(xssstrikeoutput)
forgive me if this is simple im fairly new to coding but overall but ive checked everywhere and cant seem to find a answer
variable_name = os.system(f"python3 xsstrike.py {ops} -u {website}")
This will put the required data in variable. You will be able to print it inside this function only. If you want it to print outside the function either return it or declare it as a global function.
You can do this with subprocess.check_output from the the built-in subprocess module
import subprocess
# instead of os.system
xssstrikeoutput_bytes: bytes = subprocess.check_output(f"python3 xsstrike.py {ops} -u {website}", shell=True)
xssstrikeoutput = xssstrikeoutput_bytes.decode("utf-8")
This way, you will be able to see anything that your xssstrike.py prints.
subprocess.check_output documentation
This question already has answers here:
Get fully qualified class name of an object in Python
(13 answers)
Closed 2 years ago.
I'm using Python 3.8.3 on Windows 10. I have the following code:
import # all the necessary modules
try:
# do something
except WebDriverException:
print(sys.exc_info()[0])
Upon the exception, I receive the following:
<class 'selenium.common.exceptions.SessionNotCreatedException'>
How do I get print() to output only the string within <class>?:
selenium.common.exceptions.SessionNotCreatedException
Any help would be appreciated.
To get the full path of an exception, use the inspect.getmodule method to get the package name and use type(..).__name __ to get the class name.
except WebDriverException as ex:
print (type(ex).__name__)
For the full name, try
import inspect
.....
print(inspect.getmodule(ex).__name__, type(ex).__name__, sep='.')
To keep it simple, you can just parse the string you already have
print(str(sys.exc_info()[0])[8:-2]) # selenium.common.exceptions.SessionNotCreatedException
Maybe you can try this
import # anything
try:
# something
except Exception as e:
print(e)
This question already has answers here:
Exit codes in Python
(14 answers)
Closed 4 years ago.
In C, I'd do something like
int main() {
return 42;
}
and after executing the program, I can(in Linux) prompt echo $? to the console to get the desired 42 as the return signal from the last operation. How can I do that in python?
I tried just creating a file with a return 42 in it, but it says that it is not inside a function(obviously).
exit(42)
will give you the desired behaviour.
This question already has answers here:
drop into python interpreter while executing function
(3 answers)
Closed 5 years ago.
Is there a way to cause a python script to enter the interpreter at a given line? I know I can use import pdb; pdb.set_trace() to begin debugging at a certain line, but that means all the pdb commands may get in the way.
Is there a way to kick into the regular interpreter (or ipython) outside of pdb?
The easiest way is code.interact:
import code
code.interact(local={**globals(), **locals()})
This question already has answers here:
In Python, what's the difference between 'except Exception as e' and 'except Exception, e' [duplicate]
(3 answers)
Closed 7 years ago.
I want to use Argument of an Exception to show additional information while an error occur in my code.
Here is my code.
ArgumentOfAnException.py
from pip._vendor.distlib.compat import raw_input
def to_celsius(f):
try:
c = (f-32)*5/9;
return c;
except ValueError, Argument:
print("The argumet doesn't contain number\n", Argument);
return;
f = raw_input("Enter temperature in *F : ");
print("Temperature in Celsius : ", to_celsius(float(f)));
print("Thank you...");
Here I use Argument variable to display additional information when error occur in my code but after running the program there will show a syntax error in the console output and the error is like
File "F:\Document\Files\Coding\Java Eclipse\Python Project\First Project\src\Error\ArgumentOfAnException.py", line 7
except ValueError, Argument:
^
SyntaxError: invalid syntax
It seems like you're using python 3.x.
Use following syntax (using as):
except ValueError as Argument:
Reference: try statement - Python 3 documentation