通过调用时阻止cat子流程.Popen()

2024-09-30 10:41:07 发布

您现在位置:Python中文网/ 问答频道 /正文

当linuxcat调用via时,我有一个意外的行为子流程.Popen(). 在

Python脚本的结构如下:

import os, subprocess

def _degrade_child_rights(user_uid, user_gid):
    def result():
        os.setgid(user_gid)
        os.setegid(user_gid)
        os.setuid(user_uid)
        os.seteuid(user_uid)
    return result

child = subprocess.Popen("cat /home/myuser/myfolder/screenlog.0", 
preexec_fn=_degrade_child_rights(0, 0), shell=True, 
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

当我用ps aux | grep cat检查执行的shell命令时,它显示python成功地运行了shell命令。在

^{pr2}$

然而,cat命令永远不会结束。在

我还将cat$file命令外包给bash脚本。然后bash执行我的cat调用,但也阻塞。在

当我手动执行cat$file时,它的运行与预期的一样,因此在文件末尾不存在的EOF也是不可能的。在

我认为,Popen添加的'/bin/sh-c'在某种程度上扰乱了cat$file的正确执行。在

我能阻止吗?在


Tags: 命令脚本childuidosdefshellcat
1条回答
网友
1楼 · 发布于 2024-09-30 10:41:07

您可能需要尝试Popen对象的通信方法:

Popen.communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

communicate() returns a tuple (stdoutdata, stderrdata).

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited.

^{} python doc中有更多信息

相关问题 更多 >

    热门问题