gpt4 book ai didi

process - 如何在 Idris 中调用子流程?

转载 作者:行者123 更新时间:2023-12-02 14:14:37 27 4
gpt4 key购买 nike

Idris 标准库(或第三方库)中是否有某些模块允许用户 shell 到另一个程序?我正在考虑像 Python 的 subprocess 和 Haskell 的 System.Process 这样的模块。

理想情况下,我想以编程方式与进程交互(写入其标准输入,从其标准输出读取等)。

最佳答案

有一个system : String -> IO Int函数,它接受一个shell命令,运行它,并返回它的退出代码。您需要导入 System 才能使用它:

import System

main : IO ()
main = do
exitCode <- system "echo HelloWorld!"
putStrLn $ "Exit code: " ++ show exitCode

exitCode <- system "echo HelloWorld!; false"
putStrLn $ "Exit code: " ++ show exitCode

在我的系统上,上述代码会产生以下输出:

HelloWorld!
Exit code: 0
HelloWorld!
Exit code: 256

在第二种情况下,我希望它返回 1 而不是 256。至少这是 echo $? 显示的内容。

<小时/>

可以基于Effects库制作另一个版本,其描述见this教程:

import Effects
import Effect.System
import Effect.StdIO

execAndPrint : (cmd : String) -> Eff () [STDIO, SYSTEM]
execAndPrint cmd = do
exitCode <- system cmd
putStrLn $ "Exit code: " ++ show exitCode

script : Eff () [STDIO, SYSTEM]
script = do
execAndPrint "echo HelloWorld!"
execAndPrint "sh -c \"echo HelloWorld!; exit 1\""

main : IO ()
main = run script

这里我们需要向Idris解释它需要Effects包:

idris -p effects <filename.idr>  
<小时/>

我不知道有任何 Idris 库可以让您轻松使用子进程的标准输入/标准输出。作为一种解决方法,我们可以使用 C 的管道设施,利用其 popen/pclose 函数,这些函数已经绑定(bind)在 Idris 标准库中。让我展示一下我们如何从子进程的标准输出中读取数据(请记住,这是一个带有基本错误处理的简单片段):

import System

-- read the contents of a file
readFileH : (fileHandle : File) -> IO String
readFileH h = loop ""
where
loop acc = do
if !(fEOF h) then pure acc
else do
Right l <- fGetLine h | Left err => pure acc
loop (acc ++ l)

execAndReadOutput : (cmd : String) -> IO String
execAndReadOutput cmd = do
Right fh <- popen cmd Read | Left err => pure ""
contents <- readFileH fh
pclose fh
pure contents

main : IO ()
main = do
out <- (execAndReadOutput "echo \"Captured output\"")
putStrLn "Here is what we got:"
putStr out

当你运行程序时,你应该看到

Here is what we got:
Captured output

关于process - 如何在 Idris 中调用子流程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39812465/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com