How to Execute cURL Command from Python Code

In order to execute cURL Command from your Python code you will need to make use of the subprocess module.

The subprocess module helps to create new processes and connect to their input/output/error pipes and get their return codes.

import subprocess

result = subprocess.check_output('curl', shell=True)


In the above example we have made use of the check_output method from the subprocess module with the curl command as arguments and return its output to the console.

shell=True argument tells subprocess to use a shell to execute the command.


  • Subprocess module does not work with WebAssembly, wasm32-emscripten and wasm32-wasi.
  • If the return code of subprocess.check_output is non-zero it raises a CalledProcessError.
    CalledProcessError                        Traceback (most recent call last)
    <ipython-input-4-eb1a703d34f7> in <cell line: 7>()
          6 # Execute the curl command and capture the output
    ----> 7 result = subprocess.check_output(cURL_command, shell=True)
          9 print(result.decode('utf-8'))
    1 frames
    /usr/lib/python3.9/ in run(input, capture_output, timeout, check, *popenargs, **kwargs)
        526         retcode = process.poll()
        527         if check and retcode:
    --> 528             raise CalledProcessError(retcode, process.args,
        529                                      output=stdout, stderr=stderr)
        530     return CompletedProcess(process.args, retcode, stdout, stderr)
    CalledProcessError: Command 'curl -xt' returned non-zero exit status 5.
  • Caution: Executing external commands can be a potential security risk if user input is involved, so it's important to use caution and sanitize input appropriately.



Executing cURL Command from Python Code

Have Questions? Post them here!