写入stdin并正确打印结果

2024-04-25 17:20:52 发布

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

我在一个shell中输入了一个命令./rancli -c -,其中包含以下文档:

Running the tool from the Linux shell allows additional options, depending on the options given to the command. The options are as follows:

-h Displays help about the command

-c Instead of taking typed commands interactively from a user the commands are read from the named file, i.e. in batch mode. When all commands are processed the CLI session ends automatically.

-c - As above but reads command from Linux stdin. This allows commands to be ‘piped’ to the program.

我想把它转换成python。如果我使用第二个选项,一切正常,它从文件中读取命令并在屏幕上显示结果。不过,我想使用第三个选项,它将写入stdin。我本以为这一行会运行一个命令./rancli -c - commandHere,但它没有。我要做的是输入./rancli -c -,然后我可以在下一行中手动写入stdin,比如这里我使用命令read hnb

[root@switch]# ./rancli -c -
read hnb
RAN> read hnb
               HNBId                           Location      RegUEs   ActUEs
  000295-0000038828@ipaccess.com                    n/c
  000295-0000070688@ipaccess.com                    n/c

当我把这个输入到shell中,结果就打印出来了。但是,当我在python中执行此操作时,我无法正确地将结果打印回我的计算机。以下是我尝试的:

^{pr2}$

所以当我传入这样一个命令时,它显然不像在shell中那样工作,并且被忽略了。这里有两个问题,既然我必须手动输入以下命令read hnb,我该如何将命令写到stdin?在我运行rancli -c -之后,我想在之后注入命令,我现在必须像这样键入它:

read hnb                                                                        
RAN> read hnb                   

另一个问题是,我的代码没有打印出上面的完整结果,但是当我输入下一个命令时,我会得到其余的结果和下一个结果的第一行,依此类推,在我输入下一个命令之后得到结果:

get ap                                                                          
               HNBId                           Location      RegUEs   ActUEs    
  000295-0000038828@ipaccess.com                    n/c                         
  000295-0000070688@ipaccess.com                    n/c                         
RAN> get ap 

更新:最新代码有效

cmd_rancli = ["/jffs2/usbflash0/ran/rancli", "-c", "-"]
ran_opt_get_ap = "read hnb"
proc = subprocess.Popen(cmd_rancli, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output = proc.communicate(ran_opt_get_ap)[0] 
print output

Tags: thetofrom命令comreadgetstdin
1条回答
网友
1楼 · 发布于 2024-04-25 17:20:52

要写入子进程的stdin,请将其设置为管道:

from subprocess import Popen, PIPE

p = Popen(cmd_rancli, stdin=PIPE, stdout=PIPE)
output = p.communicate(ran_opt_get_ap)[0]

^{}ran_opt_get_ap写入子进程的stdin,读取所有输出,并等待子进程完成。在

第二个问题是由缓冲引起的(只有在不同时读取所有输出时才有关系)。要修复缓冲:

相关问题 更多 >