0

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?

The Nightman
  • 5,609
  • 13
  • 41
  • 74
  • You are recursively calling your script forever. What were you hoping to do? – Paul Rooney Dec 09 '15 at 00:53
  • i am just hoping to call file2.py one time. Why is it recursively calling file2? – The Nightman Dec 09 '15 at 00:54
  • 3
    The act of performing the import in file2.py calls `system('python file2.py')`, which then launches your script again, which does the import again and so on ..... – Paul Rooney Dec 09 '15 at 00:55
  • Because you are launching file1 from file2, and file1 starts file2. This is an excellent way to shoot yourself in the foot. – Alex Huszagh Dec 09 '15 at 00:55
  • What are you trying to accomplish? – Tom Dec 09 '15 at 00:57
  • I am trying to get input variables with file1.py and then run file2.py and pass in those variables. The reason is that file2.py may or may not be submitted to another machine for processing. – The Nightman Dec 09 '15 at 00:57
  • 1
    You can use functions and a check for main to prevent the recursive calls: http://stackoverflow.com/a/419185/1747771 – Tom Dec 09 '15 at 00:59
  • If file2 doesn't have access to file1 though, how can it use the data from file1. Anyway, you should look into JSON or another data storage format if you are looking to load configurations and then run a script based on those configurations. – Alex Huszagh Dec 09 '15 at 01:00
  • @Tom that worked thanks. – The Nightman Dec 09 '15 at 01:01

1 Answers1

5

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]
Community
  • 1
  • 1
zvone
  • 18,045
  • 3
  • 49
  • 77