运行Python脚本未生成.tex文件且pdflatex调用报错,求解决
我尝试运行一份Python脚本,代码如下:
import subprocess, os with open("sometexfile.tex","w") as file: file.write("\\documentclass{article}\n") file.write("\\begin{document}\n") file.write("Hello Palo Alto!\n") file.write("\\end{document}\n") x = subprocess.call("pdflatex sometexfile.tex") if x != 0: print("Exit-code not 0, please check result!") else: os.system("start sometexfile.pdf")
运行后抛出如下错误:
line 39, in <module> x = subprocess.call("pdflatex sometexfile.tex") File "/usr/lib/python3.10/subprocess.py", line 345, in call with Popen(*popenargs, **kwargs) as p: File "/usr/lib/python3.10/subprocess.py", line 971, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/lib/python3.10/subprocess.py", line 1863, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'pdflatex sometexfile.tex'
澄清:你的.tex文件其实已经生成了
报错的根源不是.tex文件未创建,而是subprocess.call的调用格式错误,加上系统可能找不到pdflatex命令导致的。
具体原因
subprocess.call参数格式错误:
在Unix-like系统(从报错路径/usr/lib/python3.10可判断是Linux类系统)中,直接传递完整字符串命令给subprocess.call时,Python会把整个字符串当作单个可执行文件去查找,而非拆分命令和参数。它找不到名为pdflatex sometexfile.tex的文件,因此抛出FileNotFoundError。pdflatex命令不可用:
系统可能未安装TeX发行版(如TeX Live、MikTeX),或者pdflatex未加入系统PATH环境变量,导致即使命令格式正确,也无法找到该可执行文件。跨平台命令不兼容:
脚本最后用os.system("start sometexfile.pdf")是Windows专属命令,在Linux/macOS下无法正常执行PDF文件的打开操作。
验证.tex文件存在
你可以直接前往脚本运行的当前工作目录查看,sometexfile.tex应该已经存在,内容就是你写入的LaTeX代码。
修复方案
确保
pdflatex可用:
在终端中执行pdflatex --version,如果返回版本信息则说明已安装;若未安装,需先安装对应系统的TeX发行版。修正
subprocess.call调用方式(二选一):- 推荐:将命令拆分为列表形式(更安全,避免shell注入风险):
x = subprocess.call(["pdflatex", "sometexfile.tex"]) - 可选:添加
shell=True参数,让shell解析完整命令:x = subprocess.call("pdflatex sometexfile.tex", shell=True)
- 推荐:将命令拆分为列表形式(更安全,避免shell注入风险):
适配跨平台PDF打开命令:
- Linux系统:替换为
os.system("xdg-open sometexfile.pdf") - macOS系统:替换为
os.system("open sometexfile.pdf") - Windows系统:保留原命令
os.system("start sometexfile.pdf")
- Linux系统:替换为
内容的提问来源于stack exchange,提问作者TexDuinoCpp

