如何从命令行运行SWI-Prolog?

Lan*_*ard 15 shell executable command-line prolog swi-prolog

有没有办法只创建一个这样的prolog脚本hello.pl:

#!/usr/local/bin/swipl -q -s -t main

main:-
  write('Hello World\n').
Run Code Online (Sandbox Code Playgroud)

能够像这样从终端运行吗?

$ hello.pl
Hello World
$
Run Code Online (Sandbox Code Playgroud)

当我这样做时它给了我这个:

hello.pl: line 3: main:-: command not found
hello.pl: line 4: syntax error near unexpected token `'Hello World\n''
hello.pl: line 4: `  write('Hello World\n').'
Run Code Online (Sandbox Code Playgroud)

我可以通过在命令行上写这个来使它工作:

$ swipl -q -f hello.pl -t main
Hello World
$
Run Code Online (Sandbox Code Playgroud)

但有没有办法将直接脚本作为可执行文件运行?

编辑

还没有能够让这个工作.以下是@Boris在其答案评论中提出的命令的输出:

$ ls -l
total 8
-rwxr-xr-x  1 viatropos  staff  235 Aug 26 20:28 example.pl
$ cat example.pl
#!/usr/local/bin/swipl

:- set_prolog_flag(verbose, silent).

:- initialization main.

main :-
    format('Example script~n'),
    current_prolog_flag(argv, Argv),
    format('Called with ~q~n', [Argv]),
    halt.
main :-
    halt(1).
$ which swipl
/usr/local/bin/swipl
$ swipl --version
SWI-Prolog version 6.6.6 for x86_64-darwin13.1.0
$ ./example.pl
./example.pl: line 3: syntax error near unexpected token `('
./example.pl: line 3: `:- set_prolog_flag(verbose, silent).'
$
Run Code Online (Sandbox Code Playgroud)

我在Mac OSX 10.9.2上,并安装swipl与homebrew via brew install swi-prolog --with-libarchive

Cap*_*liC 11

ISO指令:初始化.这应该工作.

:- initialization main.

main :-
  write('Hello World\n').
Run Code Online (Sandbox Code Playgroud)

编辑对不起,我跳过了最有趣的细节.这是一个示例脚本,假设保存在〜/ test/main.pl中

#!/home/carlo/bin/swipl -f -q

:- initialization main.

main :-
  current_prolog_flag(argv, Argv),
  format('Hello World, argv:~w\n', [Argv]),
  halt(0).
Run Code Online (Sandbox Code Playgroud)

并使用

chmod +x ~/test/main.pl
Run Code Online (Sandbox Code Playgroud)

然后我明白了

~$ ~/test/main.pl
Hello World, argv:[]

~$ ~/test/main.pl as,dnj asdl
Hello World, argv:[as,dnj,asdl]
Run Code Online (Sandbox Code Playgroud)

在脚本中main.pl,我使用了swipl路径,该路径源自没有管理员权限的源代码构建.SWI-Prolog构建过程将bin和lib放在〜/ bin和〜/ lib下

注意:-f标志禁用加载初始化〜/ .plrc,这可能是必要的,以便对执行进行更严格的控制......

我目前不确定文档页面是否与当前的SW状态保持同步.从一些邮件列表消息,以及我自己努力重用thea,似乎命令行标志最近改变了......


小智 5

另一个答案或多或少是正确的,但是,它的工作原理可能取决于您的操作系统.最便携的方式是,有条不紊地:

$ cat example.pl
#!/path/to/your/swipl

:- set_prolog_flag(verbose, silent).

:- initialization main.

main :-
    format('Example script~n'),
    current_prolog_flag(argv, Argv),
    format('Called with ~q~n', [Argv]),
    halt.
main :-
    halt(1).
Run Code Online (Sandbox Code Playgroud)

这里的不同之处在于,除了通向swipl的路径之外,shebang线上没有任何东西.其他一切都是使用指令完成的.在我的操作系统上,只有这个工作!

$ chmod u+x example.pl
$ example.pl foo bar baz
Example script
Called with [foo,bar,baz]
Run Code Online (Sandbox Code Playgroud)

编辑

完全删除shebang行可能更简洁,而是从命令行运行:

$ swipl -s example.pl -- foo bar baz
Example script
Called with [foo,bar,baz]
Run Code Online (Sandbox Code Playgroud)

同样,使用指令设置main/0为初始化目标可以使您不必在命令行上显式执行此操作.swipl另一方面,从命令行调用可让您的操作系统找到可执行文件的位置,而不是在脚本中对此信息进行硬编码.