Ani*_*hag 2 python macos subprocess
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))
Run Code Online (Sandbox Code Playgroud)
子进程调用不起作用.这是在Mac OSX中完成的.知道为什么会这样吗?
问题
问题是〜/ Downloads路径.〜被shell环境扩展,当你调用时没有启用subprocess.call.以下是该问题的简化演示:
>>> 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
Run Code Online (Sandbox Code Playgroud)
解决方案
你可以使用两种解决方案,或者在python中使用〜os.path.expanduser或者使用参数调用subprocess.call/ .我更喜欢使用,因为它返回可能由命令生成的任何输出.以下任一解决方案都可以解决您的问题.subprocess.check_outputshell=Truecheck_outputcall
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)
Run Code Online (Sandbox Code Playgroud)