2

i have an XML file, I recovered from ftp. i want to convert this xml to json i use the xml2json

How can I call an external command from within a Python script?

python script:

#!/usr/bin/env python

import ftplib
import os

# Connection information
server = 'xxxxxx.xxxx'
username = 'xxxxxxxx'
password = 'xxxxxxxx'

# Directory and matching information
directory = '/datas/'
filematch = '*.xml'
src='/opt/scripts/'
dst='/opt/data/'

# Establish the connection
ftp = ftplib.FTP(server)
ftp.login(username, password)

# Change to the proper directory
ftp.cwd(directory)

# Loop through matching files and download each one individually
for filename in ftp.nlst(filematch):
    fhandle = open(filename, 'wb')
    print 'Getting ' + filename
    ftp.retrbinary('RETR ' + filename, fhandle.write)
    fhandle.close()

#?????????????????? EXECUTE XML2JSON TO CONVERT MY XML INTO JSON ???????????????????????
#?????????????????? xml2json -t xml2json -o stockvo.json stockvo.xml --strip_text ?????????????

#move the stockvo.xml file to destination
os.system('mv %s %s' % (src+'stockvo.xml', dst+'stockvo.xml'))

#remove the src file 
os.unlink(src+'stockvo.xml')
Mercer
  • 9,736
  • 30
  • 105
  • 170

3 Answers3

3

The subprocess module has a function for that.

You could do something like:

 import subprocess

 subprocess.call('xml2json -t xml2json -o stockvo.json stockvo.xml --strip_text', shell=True)

Please note that using the shell=True option can be a security hazard, but that depends on what you will do with your script and whether a potential user could try to do shell injection on it.

Edit: As @PadraicCunningham suggested, there's no need to use shell=True actually, since you're not using shell utilities as wildcards or ~ for home expansion. So it should work only like:

subprocess.call('xml2json -t xml2json -o stockvo.json stockvo.xml --strip_text')
cnluzon
  • 1,054
  • 1
  • 11
  • 22
0
import subprocess

 subprocess.call(['xml2json', '-t', 'xml2json', '-o', 'stockvo.json', 'stockvo.xml', '--strip_text'])
Amal Ts
  • 857
  • 1
  • 6
  • 28
0

Using subprocess module:

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)' Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute.

import subprocess

try:
    subprocess.check_call(['xml2json', '-t', 'xml2json', '-o', 'stockvo.json', 'stockvo.xml' '--strip_text'])
except subprocess.CalledProcessError:
    pass  # handle failure here
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93