简体   繁体   中英

proper way to check exit codes python3

I have a var exitcd that executes a command. Its supposed to get the exit code of running the command and then fall into one of the if/elif conditions based on that exit code.

However, it is failing stating general error occurred when the -d being used is telling me it should be hitting elif exitcd == 3 but that is not occurring.

exitcd=os.popen('cmd test ').read()
print(exitcd)
#print("retcode was {}".format(retcode))
#not found
if exitcd == 0:
    continue
# found
elif exitcd == 1:
    subprocess.Popen('cmd test -d --insecure --all-projects --json >> a_dir_res_storage')
    subprocess.Popen('cmd monitor --all-projects')
    continue
#error with command
elif exitcd == 2:
    print('error with command')
    continue
#failure to find project manifest
elif exitcd == 3:
    print('error with find manifests for {}'.format(storage+'/'+a_dir))
    continue
else:
    print('general error occurred.')

what am i doing wrong here?

Thanks

Here's a super crude example of how I've typically run external commands from Python. Using the communicate method not only allows you to get the return code from the command, but the output sent to stdout and stderr are independent.

 from subprocess import Popen, PIPE
 #
 cmd_fails = ["/bin/false"]
 run_fails = Popen(cmd_fails, stdout=PIPE, stderr=PIPE)
 out, err = run_fails.communicate()
 rc = run_fails.returncode
 print(f"out:{out}\nerr:{err}\nrc={rc}")
 #     
 cmd_works = ["/bin/echo", "Hello World!"]
 run_works = Popen(cmd_works, stdout=PIPE, stderr=PIPE)
 out, err = run_works.communicate()
 rc = run_works.returncode
 print(f"out:{out}\nerr:{err}\nrc={rc}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM