Python Forum
Code doesn't seem to write anything
Thread Rating:
  • 3 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Code doesn't seem to write anything
#1
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__":
Reply
#2
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?
Reply
#3
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:
Reply
#4
As nilamo pointed out, you never call 'main()' so nothing within the function gets done.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#5
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
Reply
#6
Should be

if __name__ == "__main__":
    main()
Also, you don't need the "self" in your function
def main()
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#7
(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.
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#8
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()
Reply
#9
I've never used json, but a quick look at the docs, shouldn't it be  json.dumps rather than  json.dump ?
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#10
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)"
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  write code that resides in parent directory franklin97355 3 419 Apr-14-2024, 02:03 AM
Last Post: franklin97355
  Last record in file doesn't write to newline gonksoup 3 455 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  needing some help to write some code for a game calculator rymdaksel 1 424 Jan-02-2024, 09:56 AM
Last Post: deanhystad
  Code works but doesn't give the right results colin_dent 2 728 Jun-22-2023, 06:04 PM
Last Post: jefsummers
  Why doesn't this code work? What is wrong with path? Melcu54 7 1,820 Jan-29-2023, 06:24 PM
Last Post: Melcu54
  color code doesn't work harryvl 1 900 Dec-29-2022, 08:59 PM
Last Post: deanhystad
  UART Serial Read & Write to MP3 Player Doesn't Work bill_z 15 5,854 Jul-17-2021, 04:19 PM
Last Post: bill_z
  My code doesn't work, can someone help me? aldasrasickas 5 2,826 Dec-21-2020, 02:26 PM
Last Post: aldasrasickas
  How to write a code with İF function? Aycaaxx 1 1,853 Nov-03-2020, 05:46 AM
Last Post: deanhystad
  Line of code to show dictionary doesn't work MaartenRo 2 2,452 Jul-28-2020, 03:58 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020