Shell 通配符不适用于 Julia 的 Shell 模式

Tom*_*Cho 5 shell julia

运行 IPython 时,我可以运行任何前面带有感叹号的 shell 命令:

In [1]: !ls
file1  file2  file3  file4

In [2]: !ls file*
file1  file2  file3  file4
Run Code Online (Sandbox Code Playgroud)

但是,某些事情(特别是使用 if 通配符)在 shell 模式下(在您输入分号之后)在 Julia REPL 上不起作用:

shell> ls file
file1 file4  file2  file3
shell> ls file*
ls: cannot access 'file*': No such file or directory
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么吗?有没有办法让通配符像在 Linux shell 中一样正常运行?

ahn*_*abb 5

你是对的,Julia shell REPL 模式不是大多数人期望的 shell,可以在这里这里找到一些讨论。目前,参数按原样传递,没有外壳扩展,因此如果程序支持正常工作的文字“*”:

shell> find -iname *
.
./file1
./file2
./file3
./file4
Run Code Online (Sandbox Code Playgroud)

如果不是,你需要想出另一种方式。就像通过 bash 调用一样:

shell> bash -c 'ls *'
file1  file2  file3  file4
Run Code Online (Sandbox Code Playgroud)

或者使用 Julia 函数/宏:

julia> bash(str::String) = run(`bash -c $str`)
bash (generic function with 1 method)

julia> macro sh_str(str::String)
       bash(str)
       end

julia> sh"ls *"
file1  file2  file3  file4
Process(`bash -c 'ls *'`, ProcessExited(0))
Run Code Online (Sandbox Code Playgroud)

  • 为了补充这个优秀的答案,不使用 shell 扩展的理由是,通过这种方式,您不依赖于系统 shell,这使您的程序更具可移植性。仅当您有“bash”时,调用“bash”的技巧才有效。正如答案所链接的问题之一中提到的,原则上可以在 Julia 的命令解析中添加常见的 Unix shell 功能(如通配符、I/O 重定向等),但这需要在跨平台中完成方式(即,不实际调用系统的外壳程序)。 (2认同)