Python Forum

Full Version: Code doesn't seem to write anything
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Please help me understand why this doesn't write the count to the status.json file.

import json
import os
import time
import datetime

# write the status file data
def main(self):
        string = {"stat":[]}
        count = 0
        while True:
                try:
                        string["stat"] = count
                        with open("/home/pi/sprinkler/status.json", 'w') as f:
                                json.dump(string, f)
                                print(string)
                                count += 1
                                if count > 99:
                                        count = 0
                                time.sleep(2)
                except IOError as e:
                        print "I/O error({0}): {1}".format(e.errno, e.strerror)
                except ValueError:
                        print ("Can't write file status.json")

if __name__=="__main__":
You never call main().

In case you just copied part of your code and not all of it, please give us more details. What messages do you get? What errors? What's the contents of the file after running?
I am troubleshooting a problem between RPi and Windows. The problem is complex so I wrote the code in the original post to simplify troubleshooting.  The sketch runs on a RPi and all it does is write an incrementing number to the file status.json and the console output every 2 seconds. That's it, nothing special about it.

The problem is that the status.json file always comes up empty as in NO data at all inside it. There are no error codes generated. I know main is running because the print command is sending the number that was supposed to be written to the file to the console every two seconds. That number was supposed to be written to the json file by the json dump command..

Can't figure out why I am not getting the data into the json file. 

I hope that clarifies what I am trying to do.

BTW:
As nilamo pointed out, you never call 'main()' so nothing within the function gets done.
I appreciate the comments that I am not calling main so nothing is running.  

I need help understand that because the print to the console in main is working as expected. How is it possible to not call main and yet have main running? I do not understand the logic of that.

From my limited python knowledge, I thought the last line called main when the script loaded. If that is not how it is supposed to be done, please demonstrate the correct way.

Thanks
Should be

if __name__ == "__main__":
    main()
Also, you don't need the "self" in your function
def main()
(May-10-2017, 09:04 PM)PickyBiker Wrote: [ -> ]From my limited python knowledge, I thought the last line called main when the script loaded.
It's a convention that comes from C - to call entry point to you code main. And even in C it's just a convention - you have to define it as an entry point in your makefile.

In Python, the "magic" variable __name__ is set by interpreter to __main__ when you run your code directly - this condition protects the code under it from being run when a module is imported.

In small executable modules, it is not necessary - you could have just written everything between lines 8 and 23 at  the module level, without wrapping it in a function. Or you could have skipped the if part and just called

main()
This construct
if __name__ == "__main__":
   <do something>
is often used to execute unittests, when you call module directly.
Okay, thank you to all. Here is the corrected code with a call to main. The problem was I inadvertently left out the call to main when I posted my code, but it was actually in my code. I also remove the self as suggested.  

Now, why doesn't this code put data into the status.json file, but it does send the code to the terminal via the print command??

import json
import os
import time
import datetime

# write the status file data
def main():
       string = {"stat":[]}
       count = 0
       while True:
               try:
                       string["stat"] = count
                       with open("status.json", 'w') as f:
                               json.dump(string, f)
                               print(string)
                               count += 1
                               if count > 99:
                                       count = 0
                               time.sleep(2)
               except IOError as e:
                       print "I/O error({0}): {1}".format(e.errno, e.strerror)
               except ValueError:
                       print ("Can't write file status.json")

if __name__=="__main__":
       main()
I've never used json, but a quick look at the docs, shouldn't it be  json.dumps rather than  json.dump ?
I'll go ahead and try that, but here is something I found on the difference between dump and dumps.

"There isn't pretty much anything else to add other than what the docs say, if you want to dump the JSON into a file/socket or whatever, then you should go for dump(). If you only need it as a string (for printing, parsing or whatever) then use dumps() (dump string)"
Pages: 1 2