忽略python中提供的输入

2024-06-16 14:29:04 发布

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

我有一个python代码,它调用一个shell脚本(get_列表.sh)这个shell脚本调用一个.txt文件,该文件的实体如下:

aaf:hfhfh:notusable:type: - city_name
hhf:hgyt:usable:type: - city_name
llf:hdgt:used:type: - city_name

当我在运行python代码之后提供输入时:

提供输入的代码:

^{pr2}$

获取输出的代码:

if List:
            try:
                    cmd = "/home/dponnura/get_list.sh -s " + "\"" + List + "\""
                    selfP = commands.getoutput(cmd).strip()

            except OSError:
                    print bcolors.FAIL + "Could not invoke Pod Details Script. " + bcolors.ENDC

它将输出显示为:

hhf detils : hfhfh:notusable:type: - city_name
aaf details : hgyt:usable:type: - city_name
llf details : hdgt:used:type: - city_name

我的要求是,如果我在执行python代码之后传递输入,并且如果我的实体不在.txt文件中,它应该将输出显示为:

如果我提供的输入为:

hhf|aaf|llf|ggg

那么对于“ggg”,它应该显示如下:

'ggg' is wrong input
hhf detils : hfhfh:notusable:type: - city_name
aaf details : hgyt:usable:type: - city_name
llf details : hdgt:used:type: - city_name

你能告诉我怎么用python或shell来做这个吗?在


Tags: 文件代码namecitytypedetailsshellusable
2条回答

你的任务可以(我认为必须)用纯Python实现。下面是其解决方案的一个可能的变体,只使用Python,不使用外部脚本或库

pipelst = str(raw_input('Enter pipe separated list  : ')).split('|')
filepath = 'test.txt'   # specify path to your file here
for lns in open(filepath):
    split_pipe = lns.split(':', 1)
    if split_pipe[0] in pipelst:
        print split_pipe[0], ' details : ', split_pipe[1]
        pipelst.remove(split_pipe[0])
for lns in pipelst : print lns,' is wrong input'

正如你所看到的,这是一个简短,简单和明确。在

这是在Python中完成的,不需要调用get_列表.sh在

import sys,re
List = str(raw_input('Enter pipe separated list  : ')).strip().split('|')
for linE in open(sys.argv[1]):
    for l1 in List:
        m1 = re.match(l1+':(.+)',linE)
        if m1:
            print l1,'details :',m1.group(1)
            List.remove(l1)
            break
for l1 in List : print l1,'is wrong input'

用法: python脚本.py文本文件.txt在

相关问题 更多 >