-1

I have a Python file Running on a Loop that prints out an estimated time for Something to happen. I would like another Python file to import just that and print it out! Exampel:

#loop.py
import datetime
import time
while 1:
    moment = datetime.datetime.now()
    next_moment = datetime.datetime.now() + datetime.timedelta(minutes = 10)
    time.sleep(50)

#Print.py
import datetime
from loop import moment, next_moment
print moment
print next_moment
print "Exit"

But if i Run Print.py it does nothing.(It should say "Exit" right?)

And if i Cancel the skript it says:

^CTraceback (most recent call last):
  File "print.py", line 2, in <module>
    from loop import moment, next_moment
  File "/home/pi/Programming/Tests/loop.py", line 8, in <module>
    time.sleep(50)
KeyboardInterrupt

So i guess by importing the scpript loop.py it also runs it. Now is there a way for me to just get the Variables out of this Loop?

Thanks for any answer!

Jonathan S
  • 13
  • 3
  • As for your observation about the module running on import, see [here](http://stackoverflow.com/questions/6523791/why-is-python-running-my-module-when-i-import-it-and-how-do-i-stop-it). Why would you want to try and pull things out of a loop running in another module like this? – roganjosh Dec 02 '16 at 18:39

1 Answers1

1

Your approach does not work because loop.py and print.py are different processes. You want inter process communication. Import in python is not about accessing data from other process, it's about loading code in-to your process from files. You can't read data that belong to another process unless that process exposes it in some specific way or unless you are debugging it.

One of possible solutions to your problem is to open a socket in loop.py and listen there for requests. print.py then will connect to the socket, send a request, receive a response with current state and print it.

Alexey Guseynov
  • 5,116
  • 1
  • 19
  • 29
  • Ok thanks. I thought because its says "from scrypt import x, y ..." it was ment to just import these variables. I will check out interprocess communication! – Jonathan S Dec 03 '16 at 16:49