-1

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

3
  • 2
    Does this answer your question? handling exit status popen python Commented Dec 20, 2020 at 1:05
  • 3
    The result of os.popen(...).read() is not an exit code. It is the stdout content from the command. Commented Dec 20, 2020 at 1:23
  • You don't have a debugger? Commented Dec 20, 2020 at 1:59

1 Answer 1

0

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}")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.