pythonunixcurl

python - Cant't take the 0 from os.system() response


I am trying to check if t is equal to "HTTP/1.1 200 OK"

import os
t = os.system("curl -Is onepage.com | head -1")
print(t)

but the response I got from os.system is

HTTP/1.1 200 OK
0

I have no idea how to take that 0 away, I've tried x = subprocess.check_output(['curl -Is onepage.com | head -1']), but it gives me this error:

Traceback (most recent call last):
  File "teste.py", line 3, in <module>
    x = check_output(['curl -Is onepage.com | head -1'])
  File "/usr/lib/python3.8/subprocess.py", line 411, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/usr/lib/python3.8/subprocess.py", line 489, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'curl -Is onepage.com | head -1'

Solution

  • os.system only returns the exit code of the spawned process, with zero usually indicating success.

    You had the right intuition with using check_output as it returns the standard output of the process, and handles non-zero exit codes by throwing an exception. Your example fails because the given command needs to run in a shell, which is not the default. As per the documentation:

    If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory.

    The following works as intended:

    import subprocessing
    output = subprocess.check_output("curl -Is www.google.com | head -1", shell=True)
    print(output)
    

    This gives:

    b'HTTP/1.1 200 OK\r\n'