如何在主

时间:2015-08-11 18:24:50

标签: haskell

我熟悉haskell的基本概念,但是很少用它来做“真实”的东西。所以现在我有一个unix可执行文件,我想在ghci中使用它并最终在main中运行它。该文件以CSV格式输出一堆东西,所以我想运行它并对输出做一些事情。到目前为止,我可以打开文件:

main :: IO ()
main = do
    let path = "pathToFile/myFile"
    yes      <- doesFileExist path
    file     <- if yes then readFile path else return ""
    print "ok!"

但文件是String键入的,这不是我想要的。所以我对下一步应该使用的库不是很熟悉。请指出我处理这类事情的方向(文档,博客等)。谢谢!

3 个答案:

答案 0 :(得分:4)

我相信您正在寻找来自procSystem.Process。要运行不带参数的脚本,请尝试

main = do
    let path = "..."
    (Just stdin, Just stdout, Just stderr, p) 
      <- createProcess $ proc path []
    putStrLn $ hgetContents stdout

这将打印脚本的输出(假设有)。在此,stdinstdoutstderr都是Handle代表各种渠道,然后可用于管理流程之间的输出。有关操作过程的更多信息,请查看System.Process文档。有关操纵Handle的更多信息,请跳至GHC.IO.Handle

以上是一种有点原始的方法,但它非常通用,应该适用于大多数用途。但是,System.Process库包含许多常见问题的快捷方式。正如melpomene在他的回答中指出的那样,更简单的readProcess函数应该足以满足您在问题中想要做的事情。

答案 1 :(得分:4)

运行程序并获取其输出的最简单方法可能是使用readProcess from System.Process

import System.Process (readProcess)

main :: IO ()
main = do
    let prog = "pathToFile/myExecutable"
    output <- readProcess prog [] ""
    putStrLn ("The output was: " ++ show output)

答案 2 :(得分:1)

我个人使用System.Process中的rawSystem https://hackage.haskell.org/package/process-1.2.3.0/docs/System-Process.html#v:rawSystem

以下是我自己的https://github.com/urbanslug/wai-devel/blob/master/src/Main.hs#L23

代码中的示例

它接受命令和参数列表。

以下是来自hackage的描述

rawSystem :: String - &gt; [String] - &gt; IO ExitCode Source

计算rawSystem cmd args运行操作系统命令cmd,使得它接收args字符串作为参数,与给定完全一致,没有有趣的转义或shell元语法扩展。因此,它在操作系统之间的行为比系统更便携。 返回代码和可能的故障与系统相同。