Search code examples
pythonpython-3.xsubprocess

Why do you keep looping out "11111"?


aaa.py:

import subprocess

print(11111)
exp = 0
subprocess.run(['python', 'bbb.py'])

print(22222)
print(exp)

bbb.py

import aaa

print("hello world")
print("bbb.py :", aaa.exp)
aaa.exp += 1

Why does it keep getting stuck in a loop?


Solution

  • Your implementation creates a circular dependency between aaa.py and bbb.py, leading to an infinite loop. Let's break down what happens step by step:

    1. aaa.py is executed.
    2. import subprocess and print(11111) are executed.
    3. exp is set to 0. subprocess.run(['python', 'bbb.py']) runs bbb.py.
    
    Now, in bbb.py:
    4. import aaa tries to import aaa.py again.
    

    Here's the problem: when bbb.py imports aaa, it executes all the code in aaa.py again, including subprocess.run(['python', 'bbb.py']). This creates a loop where aaa.py spaws a subprocess that calls bbb.py, and bbb.py imports aaa.py, leading to an infinite loop.

    How to fix this:

    As both the programs are accessing and changing the value of exp, you can keep exp in a separate module and import that module in both aaa.py and bbb.py.

    exp.py

    exp = 0
    

    aaa.py

    import subprocess
    import exp
    
    print(11111)
    subprocess.run(['python', 'bbb.py'])
    print(22222)
    print(exp.exp)
    

    bbb.py

    import exp
    
    print("hello world")
    print("bbb.py :", exp.exp)
    exp.exp += 1
    

    Output

    11111
    hello world
    bbb.py : 0
    22222
    0