在python中使用soffice,Command在终端中工作,但在Python子流程中不起作用

问题描述 投票:3回答:3

我在Python中遇到了libreoffice最令人沮丧的问题

当我在终端中运行以下内容时我完全没有问题,pdf文件是在我想要的地方生成的,生活很花哨:

cd /Applications/LibreOffice.app/Contents/MacOS/

./soffice --convert-to pdf --outdir {output_folder} {path_to_docx_file}/{title}.docx

但是当我试图将它添加到我的python脚本时:

SOFFICE = r'/Applications/LibreOffice.app/Contents/MacOS/soffice'

subprocess.Popen([SOFFICE, "--convert-to", "pdf", "--outdir", "{output_folder} ", "{path_to_docx_file}/{title}.docx"])

我收到一个错误说:

错误:无法加载源文件

我试过打开所有二进制文件和文件的所有权限,这仍然无法在python脚本中工作。我究竟做错了什么?

python pdf soffice
3个回答
2
投票

这是因为您需要更改当前工作目录,而不仅仅是提供命令的绝对路径。

subprocess.Popen(["/Applications/LibreOffice.app/Contents/MacOS/soffie", "--convert-to", "pdf", "--outdir", "{output_folder} ", "{path_to_docx_file}/{title}.docx"])

应该替换为:

subprocess.Popen(["soffice", "--convert-to", "pdf", "--outdir", "{output_folder} ", "{path_to_docx_file}/{title}.docx"], cwd="/Applications/LibreOffice.app/Contents/MacOS/")

即使它看起来非常相似,但这两个调用之间存在重大差异:当前工作目录。

使用脚本:

subprocess.Popen(["/Applications/LibreOffice.app/Contents/MacOS/soffie", "--convert-to", "pdf", "--outdir", "{output_folder} ", "file.docx"])

如果你在〜目录中调用python脚本,它将尝试访问〜/ file.docx。

但是,在第二个:

subprocess.Popen(["soffice", "--convert-to", "pdf", "--outdir", "{output_folder} ", "file.docx"], cwd="/Applications/LibreOffice.app/Contents/MacOS/")

它将尝试访问“/Applications/LibreOffice.app/Contents/MacOS/file.docx”中的文件,这与您使用cd命令执行的操作相同(事实上,cd命令会更改当前目录,所以给出cwd参数与进行cd调用相同)。

您也可以为所有文件使用绝对路径,它也可以解决问题,但这不是您想要做的。这取决于您尝试构建的软件及其目的。

这就是提示说文件不存在的原因。该程序无法在WHERE_YOU_CALL_THE_SCRIPT/{path_to_docx_file}/{title}.docx中找到该文件,因为我认为该文件位于/Applications/LibreOffice.app/Contents/MacOS/{path_to_docx_file}/{title}.docx中。


0
投票

我遇到了同样的问题。 (我使用绝对路径,所以亚历克西斯的答案并没有为我解决问题)。

经过大量的实验,我发现使用os.system而不是subprocess.Popen不会引发同样的问题,所以也许这可以用作快速修复。

更详细地说,我创建了以下可在我的环境中工作的方法。

def makePdfFromDoc_linux_batch(input_folder_path, target_folder_path):
    input_folder_files = os.path.join(input_folder_path, "*.doc")
    os.system("/Applications/LibreOffice.app/Contents/MacOS/soffice --headless --convert-to pdf --outdir " + target_folder_path + " " + input_folder_files)

但是,我没有找到解决这个问题的原因的线索。由于os.system显示不同的行为,它可能取决于subprocess.Popen生成以运行命令的环境 - 但我没有实际的证据。

我找到了this blog post,其中遇到同样的问题似乎出现在红宝石环境中。它并没有真正帮助我理解问题的根源,但实际上我很匆忙,所以它可能对你更有帮助。


0
投票

对我来说,只是缺少“libreoffice-writer”包的问题。所以,如果你在Debian上:

apt-get install libreoffice-writer

© www.soinside.com 2019 - 2024. All rights reserved.