1
votes

Python3:

Basic idea of my script is to run python script continuously, till a file parameter is set to True (using different python script, or by manually changing it in different terminal). i am trying use while loop to run until a dict key value is set to True (or Ok ..whatever). So that my python while loop keep doing the loop by checking that dict key value.

Looping works, but it doesn't stop after i change the parameter (by different terminal).

import time
import sys
import json

conffile = (eval(open('conf.ini', 'r').read()))
check = conffile.get('state')
while check == 'True':
      print("starting app")
      time.sleep(10)
      check = conffile.get('state') ##output of this check variable is 'True'
sys.exit()

cat conf.ini

{"state": "True"}

output:

starting app
starting app
starting app ......for every 10secs

Meanwhile, i changed the conf.ini dick key state to False from second terminal, so that i expect that while loop should break, but its not breaking the loop.

I have tried while check:, while check is True but no luck.. Looping continues..

Please help me to know what mistake i am doing here.

expected output:

after i change the conf.ini dict key `state` to `False`, while loop should break, program should exit.

Please Help.. Thanks in advance.

2

2 Answers

1
votes

Try this :

import time
import sys
import json

check = False
while check != 'True':
    print("starting app")
    time.sleep(10)
    conffile = (eval(open('conf.ini', 'r').read()))
    check = conffile.get('state')
sys.exit()
1
votes

You only parse the config file once at the beginning, so that won't reflect any changes later on. You have to parse it each time before you query the value. Regarding security it's also better to use ast.literal_eval.

import ast

def load_conf():
    with open('conf.ini') as fh:
        return ast.literal_eval(fh.read())

check = load_conf().get('state')