Print python version in all error messages - python

I have a python script that is called by the user by for example python script.py or python3 script.py. If this script raises an error, it is of importance which python version was used.
Surely, I could ask the user for the command that was used to execute script.py, however this might not resolve the python version. python could be an alias for python3.4 or python2.7.
I know that I could just print sys.version in my script. But I do not want to print it in every run of that script, just in the case where an error has occurred.
So another idea was to simply wrap the whole script in an try, except block.
import sys
try:
# original content of script.py
except:
print("Using python version {0}".format(sys.version))
raise
However that does not look very pythonic to me. So is there a more elegant solution to add sys.version to each error message?
This question is not a duplicate of How do I check what version of Python is running my script?, as I do not want to check for the version information. My script should run with all versions of python. However, a custom message (in this case sys.version) should be appended to the stacktrace.

yes.
>>> import sys
>>> sys.version
I do not want to print it in every run of that script, just in the case where an error has occurred.
Use try, except statements

You can change sys.excepthook to include the desired behavior.
Just add the following to the beginning of your script:
import sys
def my_except_hook(exctype, value, traceback):
print("Using python version {0}".format(sys.version))
sys.__excepthook__(exctype, value, traceback)
sys.excepthook = my_except_hook
If an error is raised in your code, the python version is printed in addition to the normal error message.

Related

How to fix error message "from: can't read /var/mail/pwn" [duplicate]

I am running a (bio)python script which results in the following error:
from: can't read /var/mail/Bio
seeing as my script doesn't have anything to with mail, I don't understand why my script is looking in /var/mail.
What seems to be the problem here? i doubt it will help as the script doesn't seem to be the problem, but here's my script anyway:
from Bio import SeqIO
from Bio.SeqUtils import ProtParam
handle = open("examplefasta.fasta")
for record in SeqIO.parse(handle, "fasta"):
seq = str(record.seq)
X = ProtParam.ProteinAnalysis(seq)
print X.count_amino_acids()
print X.get_amino_acids_percent()
print X.molecular_weight()
print X.aromaticity()
print X.instability_index()
print X.flexibility()
print X.isoelectric_point()
print X.secondary_structure_fraction()
what is the problem here? bad python setup? I really don't think it's the script.
No, it's not the script, it's the fact that your script is not executed by Python at all. If your script is stored in a file named script.py, you have to execute it as python script.py, otherwise the default shell will execute it and it will bail out at the from keyword. (Incidentally, from is the name of a command line utility which prints names of those who have sent mail to the given username, so that's why it tries to access the mailboxes).
Another possibility is to add the following line to the top of the script:
#!/usr/bin/env python
This will instruct your shell to execute the script via python instead of trying to interpret it on its own.
I ran into a similar error when trying to run a command.
After reading the answer by Tamás,
I realized I was not trying this command in Python but in the shell (this can happen to those new to Linux).
Solution was to first enter in the Python shell with the command python
and when you get these >>>
then run any Python commands.
Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.
./manage.py shell
and only then
>>> from django.contrib.sites.models import Site
Put this at the top of your .py file (for Python 2.x)
#!/usr/bin/env python
or for Python 3.x
#!/usr/bin/env python3
This should look up the Python environment. Without it, it will execute the code as if it were not Python code, but shell code. If you need to specify a manual location of the Python environment, put
#!/#path/#to/#python
for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.
For Flask users, before writing the commands, first make sure you enter the Flask shell using:
flask shell

Unable to import Tkinter

I am using Git Bash to run some code involving Tkinter, but have been unable to run the code and have gotten the error ModuleNotFoundError: No module named 'Tkinter'. I have #!/usr/bin/env/python3 as the first line of my code, but this does not seem to help. When i type import Tkinter and import tkinter into my bash line, it returns with bash: import: command not found. When I attempt to use sudo, it responds with bash: sudo: command not found. I am not sure what to do at this point, as I have already reinstalled both git bash and python and neither seem to help.
Python's import statement is case sensitive, so it just might work if you write import tkinter instead of import Tkinter.
The reason some some tutorials use the latter is because that's how it used to be in python 2. It wasn't considered very pythonic however, since all package and module names should be lowercase, so it was changed in python 3.
Regarding the first error message joelhed's anwser should solve your problem.
You receive the second error message because you
can't directly run python commands in the bash line.
To run python commands in the command line run python first.

get stacktrace of a python program for debugging

In order to get the stacktrace of a python program, I am trying to follow this example. In the article, the author invokes the gdb as follows. However, the python version of my environment is python 3.4.4. When I type
python3.4-dbg testmyplotlib2.py &
The error message is python3.4-dbg: command not found. What's the right way to get stacktrace by using gdb.
What OS are you on? It looks like you need to install python3.4-dbg. If you are on Linux, you will need to enter:
sudo apt-get install python3.4-dbg
GDB is excellent program for debugging, but if printing traceback is the only reason you are installing GDB, do not do it, that is waay overkill. You can just import traceback and
use traceback.format_stack() to get an array of calls that lead to the location in program
use traceback.print_stack() to print it to command line
use print traceback.format_exc() to print what lead to the current exceptions (works in except clasuse)

How to get python's terminal error to be in color?

I've been working with iPython notebooks for a while and I really appreciated how the error output (if I made a spelling/syntax error) was in color like this:
However, when I run code from the terminal (because ipython cannot do everything yet), I don't get any color, like so:
Of course that might vary by terminal/operating system, but I was curious if there are any easy package/plugin to make python error output in the terminal to be in color please? or even what to look for (I run zsh on ubuntu).
Digging through the IPython API reference turns up IPython.core.ultratb, the module IPython itself uses for colorful exception formatting. You should be able to do
try:
import IPython.core.ultratb
except ImportError:
# No IPython. Use default exception printing.
pass
else:
import sys
sys.excepthook = IPython.core.ultratb.ColorTB()
to check whether IPython is available, and if so, use its exception printer.

import sys error in pycharm 2.5.1

I'm a newbie using python and ubuntu, and I'm trying to import sys to my code , but it always gave me an error with the element that is using sys:
import sys
Q = sys.argv[1]
the error came with every statement that is using the sys, even when I comment the one that has the error, the one after it then will have an error ...
Q = sys.argv[1]
the error:
"IndexError: list index out of range"
Q: Is there anyway to import sys to the pycharm ??
Q: What are the prerequisite of it?
This has nothing to do with the import. sys.argv[1] is the first argument provided to the Python script.
So if you do (for example)
C:\Python27> python.exe myscript.py Hello!
then sys.argv is ["myscript.py", "Hello!"], so sys.argv[1] is "Hello!".
If you don't provide an argument, then sys.argv will just be ["myscript.py"] - consequently, you can't access sys.argv[1] because it doesn't exist.
You have imported sys correctly. The error occurs when tying to access sys.argv[1], which is an argument you pass to the python executable.
If you just run python scriptname.py, without any other arguments, there is no sys.argv[1].
One way is to run your code in the terminal (Mac, Linux, or Unix) or the command prompt (Windows) as mentioned in the answer above by Tim, but for Linux/Unix/Mac you take out the .exe from python as follows: python myscript.py Hello
If you still want to do something similar in PyCharm, you have to pass the arguments as follows:
From the menu bar on the top, click on Run
Then click on Edit Configurations..
A dialog box will open, and then enter your arguments inside the Script Parameters field
Click Ok or Apply
Then run, or debug your code and it will run!

Categories