CSA
CSA

Reputation: 43

capture subprocess output but print nothing to console?

I'm trying to run a curl command using subprocess. Works fine. I've got the output I need in a variable. The onlything I want is when the process runs, I don't want this printing in the console:

          % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                         Dload  Upload   Total   Spent    Left  Speed
        100   255  100   153  100   102     56     37  0:00:02  0:00:02 --:--:--    56

Here's what that part of the script looks like:

        import subprocess

        def F_createSingleTable(table_name):
         un = "test"
         pw = "testpass"
         url = "https://blah.fake.url.com:7877/services/createstable"
         size = "10"
         size_til_archive = "30"
         retention = "5"
         curl_call =\
          [\
          'curl', \
          '-k', \
          '-u', \
          (un)+":"+(pw), \
          (url), \
          '-d', \
          'name='+(table_name), \
          '-d', \
          'size='+(size), \
          '-d', \
          'size_til_archive='+(size_til_archive), \
          '-d', \
          'retention='+(retention)\
          ]
         process = subprocess.run((curl_call), check=True, stdout=subprocess.PIPE, universal_newlines=True)
         output = process.stdout
         if "already exists" in (output):
          print("table: "+(table_name)+" already exists")

if it matters the actual response I get which is stored in output is this:

        <?xml version="1.0" encoding="UTF-8"?>
        <response>
          <messages>
            <msg type="ERROR">table_name table already exists</msg>
          </messages>
        </response>

I don't need to save it, just check if 'alredy exists" is in it. Which I have and works.

Thanks

NOTE: I was originally wanting to use subprocess.call but I couldn't seem to capture the output to check if already exists was in the response

Upvotes: 0

Views: 1254

Answers (1)

manveti
manveti

Reputation: 1711

What you're seeing on the console is on stderr, not stdout. In it's normal mode, curl prints the fetched content to stdout and the transfer stats to stderr. You can either suppress the statistics with the -s/--silent flag or discard stderr by passing stderr=subprocess.DEVNULL to your subprocess call.

If you care about the stderr output, you can also capture it separately by passing stderr=subprocess.PIPE or merge it into the stdout stream (obviously not recommended for the specific use case in the question) by passing stderr=subprocess.STDOUT.

Upvotes: 1

Related Questions