Python exit codes - python

Where can I find information about meaning of exit codes of "python" process on Unix? For instance, if I do "python thisfiledoesntexist.py", I get exit code 2
Summary:
from errno import errorcode
print errorcode[2]

As stated, mostly the error codes come from the executed script and sys.exit().
The example with a non-existing file as an argument to the interpreter fall in a different category. Though it's stated nowhere I would guess, that these exit codes are the "standard" Linux error codes. There is a module called errno that provides these error numbers (the exit codes come from linux/include/errno.h.
I.e.: errno.ENOENT (stands for for "No such file or directory") has the number 2 which coincides with your example.

The Python manual states this regarding its exit codes:
Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors.
So, since you specified thisfiledoesntexist.py as a command line argument, you get a return code of 2 (assuming the file does not, in fact, exist. In that case I'd recommend renaming it to thisfiledoesexist.py. ;) )
Other that such parsing errors, the return code is determined by the Python program run. 0 is returned unless you specify another exit code with sys.exit. Python itself does not interfere.

Maybe exit code constants from os module can help you. Also have a look at sys.exit documentation.

Unfortunately, there is no 100% guarantee that Python's exit codes will be what the documentation claims they will be: os._exit allows the Python programmer to define which exit code is supposed to be used, which means python file_exists_but_claims_that_it_does_not.py could exit with os.EX_DATAERR.

Related

Fatal Python error: Can't initialize threads for interpreter when calling python from c

I tried to call python code from c, the example runs ok for sample code on my environment(python3.6), but when I integrate it into my program, I got following error when I call Py_Initialize();:
...
sem_init: Success
Fatal Python error: Can't initialize threads for interpreter
Could you provide some clues to solve this problem?
It seems the error comes from here, but I am still not sure how to avoid this.
The failing code is
if (head_mutex == NULL)
Py_FatalError("Can't initialize threads for interpreter");
Searching the code back for head_mutex references finds
#define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
which is called right before the failing code.
So, the reason is that PyThread_allocate_lock returns NULL. There are a few different implementations for it in Python codebase depending on the OS and build flags, so you need to debug it or otherwise figure out which one is used in your case to track the error further to an OS call.
There is a function named sem_init in my program, which may conflict with the system library, the program runs ok after I modify the name of this function(but still not sure the reason).

PyCharm: Process finished with exit code 0

I am new to PyCharm and I have 'Process finished with exit code 0' instead of getting (683, 11) as a result (please see attachment), could you guys help me out please? Much appreciate it!
That is good news! It means that there is no error with your code. You have run it right through and there is nothing wrong with it. Pycharm returns 0 when it has found no errors (plus any output you give it) and returns 1 as well as an error message when it encounters errors.
Editors and scripts do not behave like the interactive terminal, when you run a function it does not automatically show the the result. You need to actually tell it to do it yourself.
Generally you just print the results.
If you use print(data.shape) it should return what you expect with the success message Process finished with exit code 0.
exit code 0 means you code run with no error.
Let's give a error code for example(clearly in the below image): in below code, the variable lst is an empty list,
but we get the 5 member in it(which not exists), so the program throws IndexError, and exit 1 which means there is error with the code.
You can also define exit code for analysis, for example:
ERROR_USERNAME, ERROR_PASSWORD, RIGHT_CODE = 683, 11, 0
right_name, right_password = 'xy', 'xy'
name, password = 'xy', 'wrong_password'
if name != right_name:
exit(ERROR_USERNAME)
if password != right_password:
exit(ERROR_PASSWORD)
exit(RIGHT_CODE)
I would recommend you to read up onexit codes.
exit 0 means no error.
exit 1 means there is some error in your code.
This is not pyCharm or python specific. This is a very common practice in most of the programming languages. Where exit 0 means the successful execution of the program and a non zero exit code indicates an error.
Almost all the program(C++/python/java..) return 0 if it runs successful.That isn't specific to pycharm or python.
In program there is no need to invoke exit function explicitly when it runs success it invoke exit(0) by default, invoke exit(not_zero_num) when runs failed.
You can also invoke exit function with different code(num) for analysis.
You can also see https://en.wikipedia.org/wiki/Exit_(system_call) for more details.
What worked for me when this happened was to go to
Run --> Edit Configurations --> Execution --> check the box Run with
Python Console (which was unchecked).
This means that the compilation was successful (no errors). PyCharm and command prompt (Windows OS), terminal (Ubuntu) don't work the same way. PyCharm is an editor and if you want to print something, you explicitly have to write the print statement:
print(whatever_you_want_to_print)
In your case,
print(data.shape)
I think there's no problem in your code and you could find your print results (and other outputs) in the tab 5: Debug rather than 4: Run.
I just ran into this, but couldn't even run a simple print('hello world') function.
Turns out Comodo's Firewall was stopping the script from printing. This is a pretty easy fix by deleting Python out of the Settings > Advanced > Script Analysis portion of Comodo.
Good Luck
I had same problem with yours. And I finally solve it
I see you are trying to run code "Kaggle - BreastCancer.py"
but your pycharm try to run "Breast.py" instead of your code.
(I think Breast.py only contains functions so pycharm can run without showing any result)
Check on tab [Run] which code you are trying to run.
Your starting the program's run from a different file than you have open there. In Run (alt+shift+F10), set the python file you would like to run or debug.

Verifying the existance of a file or folder using subprocess library in python

I can check the presence of a file or folder using OS library very easily.
The following two links have described that
directoryExistance fileExistance
I am attempting to use the subprocess library to do the same
and, I tried a couple of approaches already
1- status = subprocess.call(['test','-e',<path>]), which is always returning 1, no matter what I pass in path.
2- Using getstatusoutput,
/bin/sh: 1: : Permission denied
status, result = subprocess.getstatusoutput([<path>])
print(status)
print(result)
which is working fine because status variable returns 126 if the file/folder exist and 127 when the file/folder doesn't exist. Also the result variable contains message but the "result" variable contains the message : Permission denied
But the second solution looks like a hack to me. Is their a better way, of doing this ?
The test command is a shell builtin, and on many platforms doesn't exist as an independent command you can run.
If you use shell=True to use the shell to run this command, you should pass in a single string, not a list of tokens.
status = subprocess.call("test -e '{}'".format(path), shell=True)
This will produce a malformed command if path contains any single quotes; try path.replace("'", r"\'") if you want to be completely correct and robust, or use one of the existing quoting functions to properly escape any shell metacharacters in the command you pass in.
The subprocess library now offers a function run() which is slightly less unwieldy than the old legacy call() function; if backwards compatibility is not important, you should probably switch to that... or, as several commenters have already implored you, not use subprocess for this task when portable, lightweight native Python solutions are available.
As pointed in the comments section
status = subprocess.call(['test','-e',<path>])
can be made to work with a shell expansion if we use "shell=True"
Although using os.path might be much more efficient anyways.

Nosetest: Does it set the errorlevel to 1 on failure?

Windows environment, python 2.7, latest nosetest.
Looking at nosetest docs, and googling around, nowhere do I see that nosetest sets the cmd line errorlevel on test failure.
We need this so that our build system can detect test failure.
Questions are:
Does Nosetest set the cmd line, errorlevel? (if so, where are docs)
If not, what is the appropriate way to handle this? (must my build parse some log output, or?)
%errorlevel% on windows is the return code of the application, typically the argument given to the exit(int) call (exit code). These return codes are the same as unittest, but the documentation is not very explicit:
The testRunner argument can either be a test runner class or an already created instance of it. By default main calls sys.exit() with an exit code indicating success or failure of the tests run.
In the above sentence By default is to understand as if the call argument exit is not set to False:
main supports being used from the interactive interpreter by passing in the argument exit=False. This displays the result on standard output without calling sys.exit()
(New in 2.7 and 3.1. In older version, sys.exit is always called.)
I found no special documentation about the return code, but looking at the source, one can find that exit code is 0 for success, 1 for error (same for unittest alone) and 2 if the usage help has to be printed (given arguments when calling as standalone program are incorrect). Specific for nose, when program is asked to display version or list plugins, exit code is 0 too.

IOError: [Errno 22] Invalid Argument with clock() being passed in

I have not had much luck hunting for finding a good explanation of what invalid argument errors are and what would cause them.
My current sample I am working with is
import sys
mylog="mylog.log"
sys.stdout = open(mylog,'w')
#lots of code
#.
#.
#.
#End of lots of code
from time import clock
print "blablabla",clock()
I receive an IOError Invalid Argument error on the clock line. I have also tried
print "blablabla\t%s"%clock()
Any information about this error would be great help. Those lines work perfectly fine on short runs, it just after running the code for a while it breaks. I have tried to setting the buffer size to something low like 45-100 lines.
I can't reproduce this exact problem on my own computer, so I can't give specific advice, but here is some general commentary on how to debug this sort of thing.
When you see "Invalid argument" in an IOError or OSError exception from python, that means the interpreter tried to make a system call, which failed and set errno to the code EINVAL. (Tangentially, python really shouldn't print the numeric values for errno codes - the symbolic names are standardized but the numbers aren't.) The first thing you need to do is find out which system call it was, and the easiest way to do that is run your program under the strace utility, like this:
$ strace -f -o strace.log python yourscript.py [arguments...]
Wait for it to fail, then search the file strace.log for "-1 E" (exactly that string). You will find something like this:
times({tms_utime=162, tms_stime=123, tms_cutime=0, tms_cstime=0}) = 1718279979
write(1, "2.85\n", 5) = -1 EINVAL (Invalid argument)
You then read the man page for the system call that failed ("man 2 write" in this case) and look for the errno code name (EINVAL in this case), and see what it says has gone wrong.
In this case I strongly suspect you have found a bug in either the Python interpreter or the operating system. "Invalid argument" means what it says - one of the input arguments to the system call had an invalid value. You're not doing anything tricky in your script, so either the interpreter is messing up its system calls, or the kernel misunderstood what the interpreter wanted.

Categories