Python Popen使用PIPE问题

时间:2017-09-27 09:48:11

标签: python popen

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

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

当从命令行运行它时,我得到了预期的结果:

Sent Disconnect-Request Id 17 from 0.0.0.0:59887 to 1.1.1.1:3799 length 44

我想从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)

但是,我必须正确地做这个"结果"变量包含radclient使用信息,就像它被错误地调用一样:

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

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

谢谢!

1 个答案:

答案 0 :(得分:1)

除了 @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时可能出现的死锁。