使用PIPE issu的Python Popen

2024-09-26 17:49:03 发布

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

我尝试使用python和Popen复制此命令:

echo "Acct-Session-Id = 'E4FD590583649358F3B712'" | /usr/local/freeradius/bin/radclient -r 1 1.1.1.1:3799 disconnect secret

从上面的命令行运行此命令时,我得到预期的:

^{pr2}$

我想通过python脚本实现同样的效果,所以我将其编码如下:

rp1 = subprocess.Popen(["echo", "Acct-Session-Id = 'E4FD590583649358F3B712'"], stdout=subprocess.PIPE)
rp2 = subprocess.Popen(["/usr/local/freeradius/bin/radclient",
                     "-r 1",
                     "1.1.1.1:3799",
                     "disconnect",
                     "secret"],
                     stdin = rp1.stdout,
                     stdout = subprocess.PIPE,
                     stderr = subprocess.PIPE)

rp1.stdout.close()

result = rp2.communicate()

print "RESULT: " + str(result)

但是,我必须不正确地执行此操作,因为“result”变量包含radclient用法信息,好像它被错误地调用了一样:

RESULT: ('', "Usage: radclient [options] server[:port] <command> [<secret>]\n  <command>....

有人知道我的错误在哪里吗?在

谢谢!在


Tags: 命令echoidsecretsessionusrstdoutresult
1条回答
网友
1楼 · 发布于 2024-09-26 17:49:03

除了@Rawing捕捉args输入错误之外,您还可以通过一个Popen进程使其更简单。试试这个:

rp = subprocess.Popen(["/usr/local/freeradius/bin/radclient",
                     "-r",
                     "1",
                     "1.1.1.1:3799",
                     "disconnect",
                     "secret"],
                     stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)

result = rp.communicate("Acct-Session-Id = 'E4FD590583649358F3B712'")

使用communicate来处理所有的I/O,可以防止在显式写入stdin时可能出现的死锁,而当您还需要从stdout/stderr中读取数据时,可能会出现死锁。在

相关问题 更多 >

    热门问题