总结。为什么 FastScripts application执行以下操作,是否有目的,我或 FastScripts 开发人员能否以某种方式修复/更改行为以不执行此操作? (否则我发现 FastScripts 是一个极好的应用程序。我正在运行 MacOS 10.9.5。)
详细信息。
FastScripts 2.6.8 似乎将当前运行的脚本内容复制到stdin对于在所述脚本中运行的任何子进程,如下面的命令行 session 所示。这不仅很奇怪,而且在开发由 FastScripts 指令触发的软件时会造成严重的困惑。
我没有用非 Python 脚本测试过类似的行为,但我编写的多个独立 Python 程序的行为方式都是相同的。我将通过电子邮件将这个问题的链接发送给 FastScripts 开发人员/技术支持。
下面是脚本正常运行的演示:
$ cat test_subprocess_stdin.py
#!/usr/bin/env python
import subprocess
cmd1 = '/tmp/reprint_stdin.py >/tmp/cmd1out.txt'
cmd2 = '/tmp/reprint_stdin.py </dev/null >/tmp/cmd2out.txt'
subprocess.Popen(cmd1, shell=True)
subprocess.Popen(cmd2, shell=True)
$ cat /tmp/reprint_stdin.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
# from http://stackoverflow.com/a/17735803/605356
stdin_content_present = not sys.stdin.isatty()
if stdin_content_present:
for line in sys.stdin:
sys.stdout.write('stdin: ' + line)
$ ./test_subprocess_stdin.py
$ cat /tmp/cmd1out.txt
$ cat /tmp/cmd2out.txt
$
但是,从 FastScripts 运行上述脚本时会发生奇怪的事情:
$ # <now running test_subprocess_stdin.py from FastScripts keyboard shortcut>
$
$ cat /tmp/cmd1out.txt
stdin: #!/usr/bin/env python
stdin: import subprocess
stdin: cmd1 = '/tmp/reprint_stdin.py >/tmp/cmd1out.txt'
stdin: cmd2 = '/tmp/reprint_stdin.py </dev/null >/tmp/cmd2out.txt'
stdin: subprocess.Popen(cmd1, shell=True)
stdin: subprocess.Popen(cmd2, shell=True)
$ cat /tmp/cmd2out.txt
$
$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.9.5
BuildVersion: 13F1077
$
注意调用os.system()代替 subprocess.Popen()导致相同的异常行为。
出于某种原因,FastScripts 并且只有 FastScripts 似乎将其正在运行的脚本的内容(在上述情况下为 test_subprocess_stdin.py )定向到被调用的任何(子)脚本的标准输入在顶层脚本/程序中。 (</dev/null 指示被调用的下标忽略 stdin。)这很奇怪,正因为如此,我花了很多开发和调试时间来发现为什么我的 FastScript 调用程序出错了。
请您参考如下方法:
感谢您提出这个有趣的问题。我已经下载并确认了您所看到的相同行为,目前正在尝试理解它。
FastScripts 运行 shell 脚本的方式是从 #! (shebang) 在脚本中行要运行的工具的名称,然后简单地运行该工具,将脚本文件的内容作为标准输入提供给正在运行的工具。因此,例如在您的示例中,它将运行:
/usr/bin/env python
以文件内容作为标准输入。
据我所知,这是调用 shell 工具运行任意基于脚本的命令的一种非常传统的方法。那么为什么 FastScripts 的行为不同于例如从命令行运行该工具?我不知道。
显然有充分的证据表明子进程确实继承了它们的父进程,例如stdin ( https://unix.stackexchange.com/questions/58252/what-sets-a-childs-stderr-stdout-and-stdin ),所以当 env 运行 python 并且反过来 python 运行子进程调用时,标准输入应该保持事件状态并不神秘。
我的问题是在直接从命令行运行脚本的情况下发生了什么不同?我不知道 shell 脚本执行的标准实现是否做了一些特殊的事情来防止将 stdin 传播到脚本本身。我得调查一下。
