Python Popen 使用 PIPE 问题
Python Popen using PIPE issue
我正在尝试使用 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)
但是,我一定是做错了,因为 "result" 变量包含 radclient 使用信息,就好像它被错误地调用了一样:
RESULT: ('', "Usage: radclient [options] server[:port] <command> [<secret>]\n <command>....
有人知道我的错误在哪里吗?
谢谢!
除了 @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 可以防止当您还需要从 stdout
/[= 读取时显式写入 stdin
时可能出现的死锁14=].
我正在尝试使用 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)
但是,我一定是做错了,因为 "result" 变量包含 radclient 使用信息,就好像它被错误地调用了一样:
RESULT: ('', "Usage: radclient [options] server[:port] <command> [<secret>]\n <command>....
有人知道我的错误在哪里吗?
谢谢!
除了 @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 可以防止当您还需要从 stdout
/[= 读取时显式写入 stdin
时可能出现的死锁14=].