OSX 上的 python 和 echo -n

标签 python ruby bash unix zsh

上下文:我跑了 this snippet在我的 Mac 上,注意到乱码输出中散布着字符串 -n 。答案是 Ubuntu 上的 sh 可以理解 -n 标志,而 Mac 上的 sh 则不能。

enter image description here

如您所见,Python 正在向标准输出发送字符串 "-n abc\n" 而不是预期的 "abc"

os.system调用是否无法分离-nabc? zsh(倒置的 % 是 zsh 表示 EOF 的方式)和 bash 都会发生这种情况,不过如果我没记错的话,python 调用不应该调用任何 shell(不是因为我读到了任何内容)所以,但基于我的常识)(编辑:事实证明我完全错了,系统运行了一个子shell)

看看 ruby​​ 是如何做的:

enter image description here

还有更多测试:

enter image description here 看起来脚本已发送到 sh,但此时 shell 的环境变量仍然是 zsh。说得通。我没有采取任何措施来清理环境...也许 sh 不会自动设置 $SHELL

最佳答案

The Python docs状态:

[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.

重点是我的。

The man page for echo解释一下:

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/

相关文章:

python - python 3.x 的任何遗传算法模块?

python - 无法理解Python的那行代码

python - 未找到名为 "interval"的触发器

ruby-on-rails - 从 Heroku 建立与/Amazon s3 的连接

Ruby ERB - 创建一个 content_for 方法

macos - 使用 mdls 命令生成元数据报告

linux - 如何修复 "file.cmpr: unknown suffix -- ignored"

mysql - 在 bash 中打印结构化 SQL SELECT 的简单方法

python - 如何合并两个 python 迭代器?

ruby-on-rails - i18n-tasks 无法路由键