为什么一个简单的 Python/Haskell/etc 程序在导入时会 freeze/hang?

why does a simple Python/Haskell/etc program freeze/hang when doing an import?

为什么这个 Python 程序 freeze/hang:

$ ls -l freeze.py
-rwx------ 1 rick rick 24 Oct 27 11:40 freeze.py
$ cat freeze.py
import re
print "hello"
$ ./freeze.py
  C-c

为什么这个 Haskell 程序也 freeze/hang:

$ ls -l freeze.hs
-rwxrw-r-- 1 rick rick 46 Oct 27 11:22 freeze.hs
$ cat freeze.hs
import Text.Regex.Posix
main = print "hello"
$ ./freeze.hs
  C-c

(我知道这是一个 rudimentary/rookie 错误。但我怀疑我是第一个或最后一个犯这个错误的人......所以我会在这里记录下来,以便将来像我这样的笨蛋google它。)

这些脚本冻结,因为它们实际上是 shell 脚本。这些 shell 脚本实际上是 运行 import 命令行程序...由 ImageMagick 软件包提供:

$ sh freeze.hs
  C-c
$ which import
/usr/bin/import
$ man import | head -10
... import - saves any visible window on an X server and outputs it as an image file.
$ import screenshot.ps
    ... and here notice the mouse icon changes to a cross-hair icon ...
    ... so then press the mouse button to finish this operation ...
$ file screenshot.ps
screenshot.ps: PostScript document text conforming DSC level 3.0, Level 1

因此,我要感谢 ImageMagick 工作人员提供了一个漂亮、安静的命令行操作。

至少在各种基于Linux的操作系统上,这些脚本会触发import命令行程序的运行。 BSD、Windows、MacOS 等可能会有不同的反应。

下面是 正确 使用 Python 解释器和 ghc 编译器的脚本操作:

$ python freeze.py
hello
$ runghc freeze.hs
"hello"

或者,包括 #! shebang:

$ ls -l no_freeze.py
-rwx------ 1 rick rick 46 Oct 27 11:44 no_freeze.py
$ cat no_freeze.py
#!/usr/bin/env python
import re
print "hello"
$ ./no_freeze.py
hello

Haskell也是如此:

$ ls -l no_freeze.hs
-rwx------ 1 rick rick 68 Oct 27 11:26 no_freeze.hs
$ cat no_freeze.hs
#!/usr/bin/env runghc
import Text.Regex.Posix
main = print "hello"
$ ./no_freeze.hs
"hello"

在我的 MacOS 计算机上,我收到此错误,因为我的 X11 设置的某些部分尚未完成。对于那些没有安装 X11 的人,我想你会得到 command not found 错误。

$ import screenshot
Version: ImageMagick 6.9.5-0 Q16 x86_64 2016-07-02 http://www.imagemagick.org
...
import: delegate library support not built-in `' (X11) @ error/import.c/ImportImageCommand/1297.