The Nightman
The Nightman

Reputation: 5759

Running a python script from another script repeats forever

I am having trouble running a second script from a first script in python. To simplify what I'm doing the following code illustrates what I'm submitting

file1.py:

from os import system
x = 1
system('python file2.py')

file2.py:

from file1 import x
print x

The trouble is that when I run file1.py x is printed forever until interrupted. Is there something I am doing wrong?

Upvotes: 0

Views: 155

Answers (1)

zvone
zvone

Reputation: 19382

from file1 import x imports the whole file1. When it is imported, all of it is evaluated, including system('python file2.py').

You can prevent the recursion this way:

if __name__ == "__main__":
    system('python file2.py')

That will solve your current problem, however, it does not look like it is doing anything useful.

You should choose one of two options:

  1. If file2 has access to file1, remove the system call completely and simply execute file2 directly.

  2. If file2 does not have access to file1 and you have to start the file2 process from file1, then simply pass the arguments to it through the command line and don't import file1 from file2.

    system('python file2.py %s' % x)

(or, a bit better, use subprocess.call(['python', 'file2.py', x]))

In file2, you can then access value of x as:

x = sys.argv[1]

Upvotes: 5

Related Questions