如何在Python中调用经Cabal构建的Haskell可执行程序?
解决Python调用Haskell Cabal程序时的Exec format error问题
你遇到的OSError: [Errno 8] Exec format error是因为直接执行了Haskell源码文件CSVTest.hs——这不是编译后的可执行二进制文件,系统无法直接运行它。以下是两种可行的解决方案:
方案1:直接通过Cabal调用程序
既然终端中通过cabal run CSVTest执行程序,Python中可以直接复用这条命令,同时指定工作目录为ConfigV根目录(确保Cabal能找到配置文件),并捕获输出用于后续处理:
import subprocess # ConfigV根目录路径 configv_root = '/home/dayiz/ConfigV' # 替换为实际的校验文件路径 check_file = '/path/to/your/target-config.csv' try: # 调用cabal run,传递校验文件参数给CSVTest result = subprocess.run( ['cabal', 'run', 'CSVTest', '--', check_file], cwd=configv_root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True ) # 获取程序标准输出,用于后续配置文件修正 program_output = result.stdout print("程序输出:") print(program_output) # 在此添加输出处理逻辑 except subprocess.CalledProcessError as e: print(f"程序执行出错,错误信息:{e.stderr}") except Exception as e: print(f"调用失败:{str(e)}")
说明:--用于分隔Cabal命令参数和CSVTest程序的参数,确保校验文件路径能正确传递给目标程序。
方案2:直接调用编译后的可执行二进制文件
如果用户已预先构建好可执行程序,需先找到Cabal编译后的二进制文件路径(而非源码文件):
- 在终端执行以下命令获取准确路径:
cd /home/dayiz/ConfigV cabal list-bin CSVTest
该命令会输出类似/home/dayiz/ConfigV/dist-newstyle/build/x86_64-linux/ghc-9.2.8/ConfigV-0.1.0.0/x/CSVTest/build/CSVTest/CSVTest的路径,这才是真正的可执行文件。
- 在Python中调用该二进制文件:
import subprocess # 替换为cabal list-bin输出的可执行文件路径 haskell_executable = '/home/dayiz/ConfigV/dist-newstyle/build/x86_64-linux/ghc-9.2.8/ConfigV-0.1.0.0/x/CSVTest/build/CSVTest/CSVTest' # 替换为实际的校验文件路径 check_file = '/path/to/your/target-config.csv' try: result = subprocess.run( [haskell_executable, check_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True ) program_output = result.stdout # 在此添加输出处理逻辑 print("程序输出:") print(program_output) except subprocess.CalledProcessError as e: print(f"程序执行出错:{e.stderr}") except Exception as e: print(f"调用失败:{str(e)}")
内容的提问来源于stack exchange,提问作者Dayiz
相关产品推荐
相关产品推荐

