【问题标题】:Python: How to get rid of stdin lines in stdoutPython:如何摆脱标准输出中的标准输入行
【发布时间】:2016-12-08 14:18:16
【问题描述】:

我有以下代码,我想将特定目录中的所有文件夹放入一个列表中,供用户选择。下面我有一个可行的解决方案,但我担心标准输出信息可能会改变,我不想硬编码我的列表以忽略标准输入信息。

lineList = lineList[6:-3] 下面的行是我关心的。

sshCommand = "plink root@255.255.255.255-pw PASSWORD"
lsCommand = "ls -1 --color=never -d */\nexit\n"
sshProcess = Popen(sshCommand,shell=False,stdin=PIPE,stdout=PIPE)
sshProcess.stdin.write("cd /mnt/PCAPS/GroupSetup\n")
sshProcess.stdin.write(lsCommand)
sshProcess.stdin.flush()
lineList = []
for line in sshProcess.stdout.readlines():
    line = line.replace("/","")
    line = line.strip('\n')
    line = line.strip('\r')
    lineList.append(str(line))

lineList = lineList[6:-3]
while(True):
    x = 0
    for line in lineList:
        x+=1
        print "(" + str(x) + ") " + line

    network_name = raw_input("Please select which network to use: ")

    try:
        network_name = lineList[int(network_name)-1]
        networkCorrect = raw_input('You have selected %s. Is this correct? (Y/N): ' %(network_name))
        if inputYNChecker(networkCorrect):
            return network_name
        else:
            print "\nPlease select a number listed above.\n"
    except:
        print "\nPlease select a number listed above.\n"

这给了我以下输出,这就是我想要的!

Using username "root". (1) A (2) B (3) C (4) D (5) E (6) F

但是,当我的代码中没有 lineList = lineList[6:-3] 时,我得到:

Using username "root". (1) Last login: Thu Dec 8 13:59:51 2016 from 255.255.255.255 (2) cd mntPCAPSGroupSetup (3) ls -1 --color=never -d * (4) exit (5) ←]0;root@Test_Control:~[root@Test_Control ~]# cd mntPCAPSGroupSetup (6) ←]0;root@Test_Control:mntPCAPSGroupSetup[root@Test_Control GroupSetup]# ls -1 --color=never -d * (7) A (8) B (9) C (10) D (11) E (12) F (13) ←]0;root@Test_Control:mntPCAPSGroupSetup[root@Test_Control GroupSetup]# exit (14) logout (15) ←[H←[2J

除了忽略特定行之外,有没有更好的方法来摆脱标准输出的“垃圾”返回?

【问题讨论】:

  • 是您的代码尝试在远程位置查找文件夹和文件,还是您的代码与您尝试访问的文件夹和文件位于同一台机器上。
  • 它连接到远程服务器,转到特定目录,然后列出该目录中的所有文件夹。我在上面的示例中更改了 IP 和文件夹名称。
  • 也许做一个正则表达式或其他过滤函数来确定是否打印该行。 if should_print(line): print("( {} )".format(line))
  • 您可以尝试添加一些带有特殊字符串的echo 命令,您可以使用该字符串来标记列表的开头和结尾,然后在输出中搜索这些字符串。
  • 好主意马克。谢谢!

标签: python stdout stdin


【解决方案1】:

为了消除我不想要的标准输出信息,我实际上决定使用 plink 的 -m 功能,它将文件作为 bash 读取。我消除了stdin.write 命令。我现在只有以下内容:

sshCommand = "plink root@XXX.XXX.XXX.XXX -pw PASSWORD -m getNetworkName.txt "
sshProcess = Popen(sshCommand,shell=False,stdin=PIPE,stdout=PIPE)

getNetworkName.txt 包含的位置:

cd /mnt/PCAPS/GroupSetup
ls -1 --color=never -d */
exit

这是我之前用sshProcess.stdin.write()写的命令

这反过来又给了我一个干净的回报

(1) A
(2) B
(3) C
(4) D
(5) E
(6) F

【讨论】:

    猜你喜欢
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 2021-12-13
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多