子流程调用失败 [英] Subprocess call fails

查看:49
本文介绍了子流程调用失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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))

子流程调用不起作用.这是在Mac OSX中完成的.知道为什么会这样吗?

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

推荐答案

问题

问题是〜/Downloads路径.〜是由调用 subprocess.call 时未启用的shell环境扩展的.下面是该问题的简化演示:

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

解决方案

您可以使用两种解决方案,或者使用 os.path.expanduser 在python中扩展〜,或者调用 subprocess.call / subprocess.check_output ,参数为 shell = True .我更喜欢使用 check_output 而不是 call ,因为它会返回该命令可能产生的所有输出.以下任何一种解决方案都可以解决您的问题.

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)

这篇关于子流程调用失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆