I want to do os.popen("gcc command") on a C file but if it fails for any reason I want to print a message and exit the program
I don't want the error to print on the console just my message and exits.
if os.path.exists(prog_path):
command_result = os.popen("gcc -Wall -Werror -std=c11 " + prog_path + " -lm")
result = command_result.read().strip()
else:
print("failed to compile your code")
exit()
I currently have this which just checks if the file exist, but doesn't check if there are any errors with the file itself.
Is there a way to check for all errors?
p.s. I tried try except and it doesn't work
gcc should finish with a non-zero exit code if compilation fails. I would just check that value.
You need to use something like subprocess.popen
to retrieve the exit code; os.popen
can't get it to you. Some related questions:
handling exit status popen python
Running shell command and capturing the output (the section on subprocess.run
)