【问题标题】:Running executable files using Haskell使用 Haskell 运行可执行文件
【发布时间】:2023-03-23 10:30:01
【问题描述】:

假设有一个 C++ 代码,我使用以下代码编译成可执行文件:

g++ test.cpp -o testcpp

我可以使用终端运行它(我使用的是 OS X),并提供一个输入文件以在 C++ 程序内部进行处理,例如:

./testcpp < input.txt

我想知道这样做是否可能,从 in Haskell。我听说过System.Process 模块中的readProcess 函数。但这仅允许运行系统 shell 命令。

这样做:

out <- readProcess "testcpp" [] "test.in"

或:

out <- readProcess "testcpp < test.in" [] ""

或:

out <- readProcess "./testcpp < test.in" [] ""

抛出此错误(或非常相似的错误,具体取决于我使用上述哪个错误):

testcpp: readProcess: runInteractiveProcess: exec: does not exist (No such file or directory)

所以我的问题是,Haskell 是否可以这样做。如果是这样,我应该如何以及使用哪些模块/功能?谢谢。

编辑

好的,按照 David 的建议,我删除了输入参数并尝试运行它。这样做很有效:

out <- readProcess "./testcpp" [] ""

但我仍然坚持提供输入。

【问题讨论】:

  • 在第一部分中,您有一个名为 test 的可执行文件,而在第二部分中,您尝试运行一个名为 testcpp 的可执行文件。这个对吗?另外我认为您需要阅读 test.in 的内容,然后将该字符串作为最后一个参数传递,而不是给出文件名。
  • @DavidYoung 是的,我只是提供了我正在尝试做的一般示例。但由于它似乎令人困惑,我对其进行了编辑。至于你评论的第二部分,你不太明白。 AFAIK,问题在于运行 exec 文件本身,而不是提供输入参数。
  • 您可以随时使用 shell 脚本创建文件,然后运行 ​​it

标签: shell haskell command-line-arguments executable


【解决方案1】:

documentation for readProcess 说:

readProcess
  :: FilePath   Filename of the executable (see RawCommand for details)
  -> [String]   any arguments
  -> String     standard input
  -> IO String  stdout

当它要求standard input 时,它不是要求从文件中读取输入,而是要求文件标准输入的实际内容。

所以你需要使用readFile等来获取test.in的内容:

input <- readFile "test.in"
out <- readProcess "./testcpp" [] input

【讨论】:

  • 是的!那行得通。感谢您的回答和明确的解释:)
猜你喜欢
  • 2012-07-04
  • 2018-06-27
  • 1970-01-01
  • 1970-01-01
  • 2018-12-31
  • 2020-10-21
  • 1970-01-01
相关资源
最近更新 更多