python - 使用 python 多处理模块缓冲/截断到文件的 Shell 脚本输出

标签 python subprocess multiprocessing

我有一个 python 框架,它必须将 bash 脚本作为插件执行。 我们正在使用 multiprocessing 模块创建工作进程,这些工作进程从 multiprocessing.JoinableQueue 中选择插件详细信息并使用 subprocess.Popen() 执行插件。

据观察,shell 脚本生成的最终输出被截断,最终结果是整个执行过程都被浪费了。

因此,我们尝试为维护子进程机制的工作人员迁移到 python 线程,以生成 shell 脚本进程。截断不再发生。但是线程非常慢(由于 GIL)并且对信号和事件的响应也是不确定的(可能是由于 GIL 发布时间)。

我在很多地方都读过,包括 stackoverflow 中的其他问题,多处理模块对 stdout 进行缓冲。我们知道这是问题所在。但是无法找到合适的解决方案,因为我们无法从 python 中为 shell 脚本必须回显到文件的数据提供 sys.stdout.flush。

我们还对一些示例尝试了 os.fsync,但没有发生截断。同样,它不能直接用于我们的目的,因为框架不知道由 shell 脚本创建的文件的名称。框架只会收回最终存档。

我的问题是,有什么方法可以防止多处理模块产生的进程中出现这种缓冲? python解释器的-u选项在这里有帮助吗?或者对/usr/lib64/python2.6/multiprocessing 中的 python 库进行任何修改都可以解决这个问题吗?

最佳答案

我们发现在脚本中通过 ssh 发送的命令在输出中被截断了。

为此我们使用了 ssh 的 -n 标志,它解决了这个问题。没有更多的截断。 但这是一个奇怪的问题,它只发生在 python 多处理环境中,任何试图将这种模型用于自己目的的人都必须认真考虑。

-n 选项的手册页说

Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The ssh program will be put in the background. (This does not work if ssh needs to ask for a password or passphrase; see also the -f option.)

关于python - 使用 python 多处理模块缓冲/截断到文件的 Shell 脚本输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10868677/

相关文章:

.net - 有什么方法可以将程序限制在一个CPU上而不关心是哪个CPU吗?

python - matplotlib:相同大小的子图?

python - 更改浮点格式以同时包含小数和逗号

python - subprocess.check_output 参数中的变量? [Python]

python - 是否可以重新定义子流程?

python - 子进程生成与父进程相同的 "random"数字

Python正则表达式排序问题

python - 使用 python 的数字到字母数字编码器(排列和正则表达式)

python - 使用 python 获取 Shell 输出

Python的多处理和内存