如何让两个python进程通过管道进行通信?

发布于 2024-09-13 23:18:19 字数 662 浏览 0 评论 0原文

我很难让它发挥作用。基本上我有一个 python 程序,需要 stdin 中的一些数据,即将其读取为 sys.stdin.readlines() 我已经对此进行了测试,并且它可以正常工作,不会出现 echo "" | 等问题。 myprogram.py

我有第二个程序,它使用子进程模块使用以下代码调用第一个程序

    proc = subprocess.Popen(final_shell_cmd,
                stderr=subprocess.PIPE, stdout=subprocess.PIPE,
                shell=False), env=shell_env)
    f = ' '.join(shell_cmd_args)
    #f.append('\4')
    return proc.communicate(f)

第二个程序是一个守护进程,我发现只要在调用第二个程序后按 ctrl-d 键,第二个程序就可以正常工作第一个程序。

因此,子进程未关闭文件似乎存在问题,并且我的第一个程序在不应该发送任何内容的情况下期望更多输入。

有人知道我怎样才能让它工作吗?

这里的主要问题是“shell_cmd_args”可能包含密码和其他敏感信息,我们不希望将这些信息作为命令名传递,因为它将显示在“ps”等工具中。

I'm having troubles getting this to work. Basically I have a python program that expect some data in stdin, that is reading it as sys.stdin.readlines() I have tested this and it is working without problems with things like echo "" | myprogram.py

I have a second program that using the subprocess module calls on the first program with the following code

    proc = subprocess.Popen(final_shell_cmd,
                stderr=subprocess.PIPE, stdout=subprocess.PIPE,
                shell=False), env=shell_env)
    f = ' '.join(shell_cmd_args)
    #f.append('\4')
    return proc.communicate(f)

The second program is a daemon and i have discovered that the second program works well as long as I hit ctrl-d after calling it from the first program.

So it seems there is something wrong with subprocess not closing the file and my first program expecting more input when nothing more should be sending.

anyone has any idea how I can get this working?

The main problem here is that "shell_cmd_args" may contain passwords and other sensitive information that we do not want to pass in as the command name as it will show in tools like "ps".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温柔女人霸气范 2024-09-20 23:18:19

您想要重定向子进程的标准输入,因此需要 stdin=subprocess.PIPE

您不需要将 Control-D ('\4') 写入文件对象。 Control-D 告诉 shell 关闭连接到程序的标准输入。该程序在该上下文中看不到 Control-D 字符。

You want to redirect the subprocess's stdin, so you need stdin=subprocess.PIPE.

You should not need to write Control-D ('\4') to the file object. Control-D tells the shell to close the standard input that's connected to the program. The program doesn't see a Control-D character in that context.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文