0

I have a python script with a function and a while loop and I want to call this function from another python script which also has a while loop. Here is an example script:

script1.py:

global printline
printline = abc

def change(x):
    global printline
    printline = x

while True:
    global printline
    print printline

And this is script2.py:

from script1 import change

change(xyz)

while True:
    print hello

When I run script2.py, it starts to print abc and doesn't go into the while loop in this script.

When I run script1.py, it prints abc.

When I run both together, in different terminals, both print abc.

I need it so that when both scripts are run, script2.py can change the variable printline while going into the while loop.

I don't know if this is the right way to do it as I'm new to python.

Thanks.

5
  • 1
    Those can't possibly be your actual scripts. Wouldn't you get "name is not defined" errors on abc and xyz? Please post the actual code you are having trouble with, verbatim, otherwise all anyone can do is guess. Commented Aug 22, 2016 at 7:21
  • Are these scripts supposed to be separate programs that share the same printline variable? As in, when both scripts run at the same time, they share the same printline variable? Commented Aug 22, 2016 at 7:22
  • Are abc and xyz supposed to be strings "abc" and "xyz"? Commented Aug 22, 2016 at 7:24
  • 1
    There's no point in putting a global statement outside a function. Commented Aug 22, 2016 at 7:25
  • 1
    When you import from a file, all the statements that aren't in functions are executed normally, just as if you ran the script by itself. So the while True: code in script1.py executes, and it never gets out of that infinite loop. Top-level statements in a module file are just expected to initialize the module, they need to finish. Commented Aug 22, 2016 at 7:28

1 Answer 1

1

When you do from script1 import change, it executes all the top-level code in script1.py. So it executes the while True: block, which loops infinitely, and it never returns back to script2.py.

You need to split up script1.py so that you can import the change() function without executing the top-level code.

change.py:

def change(x):
    global printline
    printline = x

script1.py:

from change import change

change("abc")
while True:
    print printline

script2.py:

from change import change

change("xyz");
while True:
    print printline
Sign up to request clarification or add additional context in comments.

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.