Code 0 1 in python

I am trying to add the return code and getting error message.


if os.stat(file).st.size == 0:
    return 0
else:
    return 1

What error are you getting? The first thing I spot is that you are capitalizing If when it should be if, so that is probably one problem, but posting your actual error will allow others to help better.

Sorry that if is a typo error.

SyntaxError: 'return' outside function

Is this what you’re trying to do ?

def some_function(**args):
    if os.stat(args['file_name']).st_size == 0:
        return True
    else:
        return False


file = 'some_file_name'
print(some_function(file_name=file))

… the point being that you should be using .st_size not .st.size, unless that’s OS specific, but don’t think it is.

Also, I prefer to use True and False, rather than 1 and 0 for this kind of operation, as it’s more ‘human friendly’.

Are you trying to get return code like in C main function?
If so you should replace return 0 with sys.exit(0)
See more about here

1 Like

Are you trying to issue an exit status upon terminating execution of the program? If so, does this accomplish what you need?:

sys.exit(os.stat(file).st_size and 1)

That line would replace the if and else blocks from your original post. However, some might regard the meaning of that line as cryptic. If you feel it would be clearer to use the conditional blocks, this might serve the purpose:

if os.stat(file).st_size == 0:
    sys.exit(0)
else:
    sys.exit(1)
1 Like

I have tried the below example and i have executed as below but still 0 or 1 is not returned.

Rc= python3 progname input
echo $rc

But none of the value is not recieved.

if os.stat(file).st_size == 0:
    sys.exit(0)
else:
    sys.exit(1)

Return codes are stored in $? and (AFAIK) have to be extracted from that:

dev-311 ❯ python -c "import sys; sys.exit(1)"

dev-311 ❯ echo $?
1

The testing described below was performed on a MacBook Air with the Ventura operating system.

The following code was stored in stat.py:

import os
import sys
filename = input("Name of file: ")
if os.stat(filename).st_size == 0:
    sys.exit(0)
else:
    sys.exit(1)

Two additional files were used. One was named laden_swallow.txt, and contained the following single line of text, so its size was 3:

egg

The other file was named unladen_swallow.txt, and was empty, so its size was 0.

With those files in place, the following interactive session was performed on the terminal:

% python stat.py
Name of file: laden_swallow.txt
% echo $?
1
% python stat.py
Name of file: unladen_swallow.txt
% echo $?
0

As we see, the program did return the desired codes to the system.

It works now.