4

我在 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 脚本中仍然不起作用。我究竟做错了什么?

4

3 回答 3

3

对我来说,这只是缺少“libreoffice-writer”包的问题。因此,如果您使用的是 Debian:

apt-get 安装 libreoffice-writer

于 2019-06-08T14:35:46.533 回答
2

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

subprocess.Popen(["/Applications/LibreOffice.app/Contents/MacOS/soffice", "--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.

于 2016-06-12T09:54:16.610 回答
2

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

经过大量实验,我发现使用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 为运行命令而生成的环境 - 但我没有实际证据证明这一点。

我发现这篇博文,在 ruby​​ 环境中似乎出现了同样的问题。它并没有真正帮助我理解问题的根源,但实际上我很着急,所以也许它对你更有帮助。

于 2019-04-16T14:10:11.280 回答