0

I will start by prefacing that i am a fresher with only university level python experience.

I am trying to get the error code of an os.system(cmd) to my python script.

I know that i should be using subprocess, but in my current scenario i have a limitation of using only os. The issue is that the 404 Not Found is being printed in my console, i just want it to be available for my script.

Here is the os command:

try:
    os.system(download_cmd)

I know i cant catch the exception but in the console this is being printed:

HTTP request sent, awaiting response... 404 Not Found
2020-07-16 14:41:03 ERROR 404: Not Found.

I need the text or code 404 Not Found to be used by my script.

Any insight will be helpful. Thanks!

GCode21
  • 64
  • 4
  • you'd have to post what the download_cmd is. 404 means that you tried to download a file which didn't exist on the server. either because it actually doesn't exist, or it exists but in a different format or other reasons. – ewokx Jul 20 '20 at 07:21
  • You might want to check this https://stackoverflow.com/questions/2502833/store-output-of-subprocess-popen-call-in-a-string – ChatterOne Jul 20 '20 at 07:23
  • The requirement to avoid `subprocess` and stick to `os` seems pretty crazy. If this is real, `os.popen()` is a thin wrapper for `subprocess.Popen()` in recent versions of Python. In earlier versions, it was deprectaed for quite a while, but did offer functionality which would let you access standard output (and IIRC standard error). – tripleee Jul 20 '20 at 07:36
  • If you want to do it the ugly way (with `os` only), you can try redirecting the output to a file with `>` and reading the file. – ChatterOne Jul 20 '20 at 08:14
  • @ewong yes I am aware of that. If the file does not exist i should handle it differently than any other exception. that is why i need to get the error code. what stupifies me is that the 404 not found is being printed on the console. If there was any way i could get that string back to the program i could make use of it. – GCode21 Jul 20 '20 at 15:38
  • @ewong the download_cmd is a simple wget to a URL – GCode21 Jul 20 '20 at 15:42

2 Answers2

0

os.system() runs the process only, it doesn't capture the output.

Ali Rida
  • 336
  • 2
  • 10
0

os.system() returns the exit code.

This is distinct from whatever is being printed; but if the dowload tool is any good, it will return zero for success, and nonzero for failure like any well-behaved CLI program.

System result codes are a single byte, so you can't get a value bigger than 255; but if you are lucky, the program you are using maps distinct HTTP error codes to distinct exit codes. Check its manual page, or, failing that, its source code.

tripleee
  • 175,061
  • 34
  • 275
  • 318