0

I want change value in Script1.py from Script2.py but Script1 always running. For example;

Script1.py

count = 0
while(count == 0):
    print (count)

Script2.py

// I want change count and break loop here when Script1.py running
1
  • 1
    you will need to have some sort of communication, its fairly easy to set up a socket connection and have script1 check if there is data on the channel and act accordingly somewhere in the loop, or even have its own thread thats always listening to the channel here is a guide with good examples Commented May 14, 2019 at 11:44

2 Answers 2

2

Write in Script2.py :

import Script1
Script1.count = 1

You should put the while loop of Script1.py inside a function or Script2.py will never exit the import statement and Script1.count will never be modified.

This lets you modify count in Scripy1.py before the loop starts. If you want to modify it while the loop is running, I don't know how to do it. But it's something you should not do.

Sign up to request clarification or add additional context in comments.

5 Comments

I don't think this changes the value of the variable in Script2 dynamically when there is a change in script1
Yes it does but the while loop must not be written with no protection in Script1.py because then Script2.py will never get out of the import statement and count will never be modified. Defining this loop in a function makes it exit the import statement correctly and then you can see it works.
If you really want it modified while the while loop is running, I think you're gonna need multiprocessing so that a worker can modify count while another runs the while loop.
@Asharhing you said : "you need some multiprocessing step to have both running together." Can you give me example on code ?
Actually I tested it and multiprocessing won't work because the while loop process will be refered to the environment state at the moment it started and the modified count won't reach it because it was done after the first process started. I don't know how to have it modified while the while loop is running. What I wrote lets you modify it before the loop starts.
1

you could try putting the variable inside another file were one script writes to the file and another just reads it.

something like this

**script 1. writes to the file**

for x in range(1,100):

    file1 = open("MyFile.txt","w") # open file as write

    file1.write(str(x))

    file1.close() # has to close or it will be appended instead of over writing it 

**script 2. reads the file**

file2=open("MyFile.txt", "r")

if file2.read==Somevalue :

   do something.


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.