要解释我想做什么有点困难,但我会尝试清楚地表达。我想在文件中查找字符串(url)并将其与其他字符串(在我的代码中命名为' services')进行比较,它实际上需要将所有服务与整个文件进行比较 如果文件中的网址不包含服务,请使用该网址执行操作(从文件中删除该额外网址)。 我的代码如下,但它没有给我正确的结果。我认为我的for循环有问题。
def search_service():
status='Y'
services = subprocess.Popen("docker-cloud service ps | awk '{print $1}'", shell=True, stdout=subprocess.PIPE)
for line in iter(services.stdout.readline, ''):
line=line.replace("\n","")
with open('nginx.conf') as f:
for word in f:
if 'proxy_pass' in word:
st=word
if re.search(line,st):
status='Y'
else:
status='N'
new=st
if 'N' in status:
print(st)
#remove_block(st)
我的DockerCloud输出服务示例:
dev-qwerty
test-asdfgh
nginx.conf:
server {
listen 80;
server_name asdfgh-test.example.com;
location / {
proxy_pass http://test-asdfgh-example.io:5002/;
proxy_redirect off;
##proxy_set_header Host $host;
blah
}
}
server {
listen 80;
server_name nginx-dev.example.com;
location / {
proxy_pass http://dev-nginx-example.io:5002/;
proxy_redirect off;
##proxy_set_header Host $host;
blah
}
}
server {
listen 80;
server_name qwerty-dev.example.com;
location / {
proxy_pass http://dev-qwerty.io:5106/;
proxy_redirect off;
##proxy_set_header Host $host;
blah
}
}
预期输出是要找出:
proxy_pass http://dev-nginx-example.io:5002/;
任何帮助都将不胜感激。
答案 0 :(得分:0)
我不完全确定我已经理解了你所问的内容,但这是否符合这些要求?
dummy_input_file = 'dummy_file.in'
with open(dummy_input_file, 'w') as out_file:
out_file.write("""\
string1
string2
string3""")
expected_sub_strings = ['ing2', 'ing3']
modified_file_name = 'modified_file.out'
with open(dummy_input_file, 'r') as in_file, open(modified_file_name, 'w') as out_file:
for line in in_file:
if any(s in line for s in expected_sub_strings):
out_file.write(line)
with open(modified_file_name, 'r') as in_file:
print(in_file.read())
打印:
string2
string3
答案 1 :(得分:0)
您的代码非常复杂,这也是一样的,并且更容易阅读:
def search_service():
services = subprocess.Popen("docker-cloud service ps | awk '{print $1}'", shell=True, stdout=subprocess.PIPE)
docker_services = []
for line in iter(services.stdout.readline, ''):
line=line.replace("\n","")
docker_services.append(line)
with open('nginx.conf') as f:
for word in f:
if 'proxy_pass' in word:
unknown = True
for service in docker_services:
if service in word:
unknown = False
break
if unknown:
print(word.strip())