如何为含Node、Perl调用的Python子脚本绑定绝对路径替代相对路径
解决方案
问题根因
代码中使用的相对路径./preprocess_latex.js默认相对于Python进程的当前工作目录,而非utils.py文件所在的目录。从项目根目录导入执行时,工作目录为项目根目录,自然找不到位于latex_utils/scripts/preprocessing下的JS文件。同时JS文件内部依赖上层目录的相对路径,不能直接修改JS文件的调用路径。
修复后代码
import os import subprocess def tokenize(latex,kind='normalize'): # 新增:获取当前utils.py所在的preprocessing目录的绝对路径 current_dir = os.path.dirname(os.path.abspath(__file__)) # 改动:将输入输出文件转为绝对路径,避免子进程工作目录变化后找不到文件 output_file = os.path.abspath('./out.lst') input_file = os.path.abspath('./input_file.lst') cmd = "perl -pe 's|hskip(.*?)(cm\|in\|pt\|mm\|em)|hspace{\1\2}|g' %s > %s"%(input_file, output_file) ret = subprocess.call(cmd, shell=True) temp_file = output_file + '.tmp' # 创建临时文件 with open(temp_file, 'w') as fout: with open(output_file) as fin: for line in fin: fout.write(line.replace('\r', ' ').strip() + '\n') # 删除换行符\r cmd = "cat %s | node ./preprocess_latex.js %s > %s "%(temp_file, kind, output_file) # 改动:新增cwd参数指定子进程工作目录为preprocessing目录 ret = subprocess.call(cmd, shell=True, cwd=current_dir) os.remove(temp_file)
改动说明
- 通过
__file__变量获取当前utils.py的绝对路径,进一步计算得到其所在的preprocessing目录路径,该值不随Python执行的工作目录变化 - 将输入输出文件路径转为绝对路径,避免子进程工作目录修改后,无法正确定位读写的文件
- 调用node命令的
subprocess.call新增cwd参数,指定子进程的工作目录为preprocessing目录:既可以让./preprocess_latex.js的相对路径正确命中目标文件,也能保证JS内部../../开头的上层相对路径按原有逻辑解析,完全兼容JS的依赖关系,无需修改任何目录结构或JS文件内容。
内容的提问来源于stack exchange,提问作者Deshwal
相关产品推荐
相关产品推荐

