2
import shlex,subprocess,os
cmd = "/Applications/LibreOffice.app/Contents/MacOS/swriter --headless --invisible --convert-to pdf:writer_pdf_Export --outdir ~/Downloads ~/Downloads/HS303.xlsx"
#This works
os.popen(cmd)
#This doesnot work
subprocess.call(shlex.split(cmd))

Subprocess calls are not working. This was done in Mac OSX. Any idea as to why this is happening ?

2
  • 3
    Please clarify "are not working". Do any subprocess calls work? What result do you get, an exception? Commented Dec 6, 2012 at 11:20
  • I did check_output but it prints ' ', answer posted below Commented Dec 6, 2012 at 14:54

1 Answer 1

5

The problem

The problem is the ~/Downloads path. the ~ is expanded by the shell environment which wasn't enabled when you called subprocess.call. Below is a simplified demonstration of the problem:

>>> import shlex, subprocess, os, os.path
>>> cmd = "ls ~/Downloads"
>>> print os.popen(cmd).read()
ubuntu-11.04-desktop-i386.iso
ubuntu-11.04-server-i386.iso

>>> print subprocess.check_output(shlex.split(cmd))
ls: cannot access ~/Downloads: No such file or directory
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/subprocess.py", line 537, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['ls', '~/Downloads']' returned non-zero exit status 2

The solutions

There are two solutions you could use, either expand the ~ in python using os.path.expanduser or call subprocess.call/subprocess.check_output with argument shell=True. I prefer to use check_output over call because it returns any output that might have been produced by the command. Either solution below should solve your problem.

import shlex, subprocess, os, os.path
cmd = 'ls ' + os.path.expanduser('~/Downloads')
print subprocess.check_output(shlex.split(cmd))

cmd = 'ls ~/Downloads'
print subprocess.check_output(cmd, shell=True)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.