【发布时间】: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命令,您可以使用该字符串来标记列表的开头和结尾,然后在输出中搜索这些字符串。 -
好主意马克。谢谢!