[Tutor] Cmd line not correctly interpreted

Peter Otten __peter__ at web.de
Sat Jun 4 04:20:00 EDT 2016


Alan Outhier wrote:

> I'm working on a Python script to call "sox" to convert ;ogg files to
> .mp3s.
> 
> In the following segment...:

To avoid garbled code as seen below please ensure that you post plain text. 
Thank you. 
> 
> *1    outname=fname+".mp3"2    fname=ReSpace(fname)   # substitute " "
> with
> "\ "3    outname=ReSpace(outname)4    cmdline="sox " + fname + " "
> +outname5    print cmdline6    rtncode=os.system(cmdline)7    if rtncode
> <>
> 0:8        print "Bad return code (" + str(rtncode) + ") from sox
> command"9        sys.exit()*
> 
> ...I DO get the error trap (every time). Line 5 causes the following (for
> example) to be printed:
> 
> 
> *sox Carnegie\ Hall\ Jazz\ Band/Carnegie\ Hall\ Jazz\ Band/Frame\ for\
> the\ Blues Carnegie\ Hall\ Jazz\ Band/Carnegie\ Hall\ Jazz\ Band/Frame\
> for\ the\ Blues.mp3*
> *Bad return code (512) from sox command *
> 
> I can however cop-past that output to bash and it works fine.
> 
> I get similar (but *as expected* more complicated problems if I comment
> out lines 2 & 3.
> 
> Please help! I'll send the whole program if requested.

The best approach is to use the subprocess module and let Python do the work 
for you. For example

import subprocess

fname = ... # may contain spaces
outname = fname + ".mp3"
# Pass arguments as a list, no need to use a shell:
subprocess.check_output(["sox", fname, outname])

If the sox invocation fails check_output will raise a CalledProcessError 
exception that you can examine for details, print or just let bubble up.



More information about the Tutor mailing list