将 shell 输出存储在变量中

Store shell output in variable

我是 prolog 的新手,正在尝试使用 Shell 函数将值读入变量。我想做的是:

  1. 运行 shell 输出 0 到多行的命令
  2. 将输出存储在变量中
  3. 继续对变量进行操作

这相当于这样的东西

$ find ./ -name "example*"
./example1
./example2

$ ls -la ./example1
$ ls -la ./example2

我可以做第一部分

find_files() :- shell("find ./ -name \"example*\" 2>/dev/null").

然后你会如何处理每一行,例如./example1./example2 然后将它们存储在变量中 运行 在另一个函数中?

是这样的吗? run_ls 不能正常工作,但这就是我要实现的逻辑。

concatenate(StringList, StringResult) :-
    maplist(atom_chars, StringList, Lists),
    append(Lists, List),
    atom_chars(StringResult, List).

run_ls(X) :- shell(concatenate(["ls ", X], String)).

find_files :- shell("find ./ -name \"example*\" 2>/dev/null"), run_ls(output_variable_from_shell).

您实际上想使用 process_create/3 not shell/1 or shell/2

然后您可以捕获子进程通过管道写入其标准输出或标准错误的任何内容。

process_create/3 页面上,Boris 给出了这个捕获输出的例子:

bash_command(Command, Output) :-
        process_create(path(bash),
                ['-c', Command],
                [stdout(pipe(Out))]),
        read_string(Out, _, Output),
        close(Out).

还有这个:

?- bash_command("echo banana | tr na bo", Output).
Output = "bobobo\n".

对于find,最好让它打印由0字符分隔的路径:

find . -print0 

然后您可以安全且轻松地将在 \x00 字符处获得的大字符串拆分为路径列表,而不必关心路径名中的空格或 CR/LF(好吧,我这么认为,它可能由于某些原因而不起作用)。