How to determine the directory in which a running Haskell script or application lives?

烈酒焚心 提交于 2019-11-29 06:27:40

There is a FindBin package which seems to suit your needs and it also works for compiled programs.

As I understand it, this is historically tricky in *nix. There are libraries for some languages to provide this behavior, including FindBin for Haskell:

http://hackage.haskell.org/package/FindBin

I'm not sure what this will report with a script though. Probably the location of the binary that runhaskell compiled just prior to executing it.

Also, for compiled Haskell projects, the Cabal build system provides data-dir and data-files and the corresponding generated Paths_<yourproject>.hs for locating installed files for your project at runtime.

http://www.haskell.org/cabal/release/cabal-latest/doc/users-guide/authors.html#paths-module

For compiled executables, In GHC 7.6 or later you can use System.Environment.getExecutablePath.

getExecutablePath :: IO FilePathSource

  Returns the absolute pathname of the current executable.
  Note that for scripts and interactive sessions, this is the path to the
  interpreter (e.g. ghci.) 

I could not find a way to determine script path from Haskell (which is a real pity IMHO). However, as a workaround, you can wrap your Haskell script inside a shell script:

#!/bin/sh

SCRIPT_DIR=`dirname $0`

runhaskell <<EOF
main = putStrLn "My script is in \"$SCRIPT_DIR\""
EOF

There is executable-path which worked with my runghc script. FindBin didn't work for me as it returned my current directory instead of the script dir.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!