1

I want to exec the command docker ps -q using python os.system function and then get its output to use it to create xml text node.

I tried xml.createTextNode(os.system("docker ps -q"):

  6 from xml.dom import minidom
  7 import os
  8
  9 xml = minidom.Document()
 10
 11 rootElem = xml.createElement('containers')
 12
 13 dataElem = xml.createElement('data')
 14
 15 idElem = xml.createElement('id')
 16 idElem.appendChild(xml.createTextNode(os.system("docker ps -q")))

But it gives me this error:

 File "scriptCreateXML.py", line 16, in <module>
    idElem.appendChild(xml.createTextNode(os.system("docker ps -q")))
  File "/usr/lib/python3.6/xml/dom/minidom.py", line 1658, in createTextNode
    raise TypeError("node contents must be a string")
TypeError: node contents must be a string

I expect the output of this

<?xml version="1.0" ?>
<containers>
    <data>
        <id>some id</id>
    </data>
</containers>
jww
  • 97,681
  • 90
  • 411
  • 885
Abderrahmane
  • 385
  • 2
  • 3
  • 14
  • 1
    You *don't* get the output of the program run by `os.system()` - it goes directly to your terminal, Python never sees it. Use one of the various functions in the `subprocess` module to actually get this output. – jasonharper Jan 12 '19 at 01:42
  • In addition to what @jasonharper said: you're capturing either a `0` for successful execution, or an integer `>0` if there was an error. – tink Jan 12 '19 at 01:44

1 Answers1

1

Modify the last line, use subprocess instead of os and use check_output instead of call

In [25]: idElem.appendChild(xml.createTextNode(subprocess.check_output(["docker","ps", "-aq"]).decode('UTF-8')))
Out[25]: <DOM Text node "'967dd77436'...">

I dont have running containers, so I have used "-aq", you can modify that as per your requirements.

Raja G
  • 5,973
  • 14
  • 49
  • 82