上下文:我跑了 this snippet在我的 Mac 上,注意到乱码输出中散布着字符串 -n
。答案是 Ubuntu 上的 sh
可以理解 -n
标志,而 Mac 上的 sh
则不能。
如您所见,Python 正在向标准输出发送字符串 "-n abc\n"
而不是预期的 "abc"
。
os.system
调用是否无法分离-n
和abc
? zsh(倒置的 %
是 zsh 表示 EOF 的方式)和 bash 都会发生这种情况,不过如果我没记错的话,python 调用不应该调用任何 shell(不是因为我读到了任何内容)所以,但基于我的常识)(编辑:事实证明我完全错了,系统运行了一个子shell)
看看 ruby 是如何做的:
还有更多测试:
看起来脚本已发送到 sh
,但此时 shell 的环境变量仍然是 zsh
。说得通。我没有采取任何措施来清理环境...也许 sh
不会自动设置 $SHELL
。
最佳答案
[
os.system
] is implemented by calling the Standard C function system()
按照the man page for C's system
进行操作:
system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed. During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.
重点是我的。
Some shells may provide a builtin echo command which is similar or identical to this utility. Most notably, the builtin echo in sh(1) does not accept the -n option. Consult the builtin(1) manual page.
您可以自己确认这一点:
$ sh -c "echo -n hello"
-n hello
$ bash -c "echo -n hello"
hello
关于OSX 上的 python 和 echo -n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867810/