要解释我想做什么有点困难,但我会试着把它表达清楚。我想在文件中查找一个字符串( url ),并将其与另一个字符串(在我的代码中命名为' services‘)进行比较,如果文件中的url不包括服务,则需要将所有服务与整个文件进行比较,对该url执行一些操作(从文件中删除多余的url)。我的代码如下所示,但它没有给出正确的结果。我想我的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-asdfghnginx.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/;任何帮助都将不胜感激。
发布于 2017-03-12 21:15:48
你的代码太复杂了,这做了同样的事情,而且更容易阅读:
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())发布于 2017-03-12 20:35:37
我不能完全确定我已经理解了你的问题,但是有没有类似的东西呢?
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
string3https://stackoverflow.com/questions/42747356
复制相似问题