Send value of variable that is in a loop from one script to another script

前端 未结 2 1271
遥遥无期
遥遥无期 2021-01-27 08:22

I\'ve been fiddling with sending a variable from one script to another and have done some basic things pretty easily, but I have gotten stuck and was hoping to get some input.

相关标签:
2条回答
  • 2021-01-27 08:57

    I finally got it to work. Thanks to going back and forth with Vadim, I was able to learn how some of this stuff works. Below is what my code is.

    script1.py:

    import sys, time
    x=0
    while x<10:
        print(x)
        sys.stdout.flush()
        x = x+1
        time.sleep(1)
    

    script2.py:

    import subprocess
    
    proc = subprocess.Popen('python script1.py', 
                            shell=True,
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            )
    while True:
        output = proc.stdout.readline()
        if output == '':
            break
        else:
            print output.rstrip()
    

    Output:

    0 #waits one second
    1 #waits one second
    2 #waits one second
    .
    .
    .
    8 #waits one second
    9 #waits one second
    
    0 讨论(0)
  • 2021-01-27 09:11

    main.py

    from subprocess import Popen, PIPE
    import sys
    
    p = Popen(['py', 'client.py'], stdout=PIPE)
    while True:
        o = p.stdout.read(1)
        if o:
            sys.stdout.write(o.decode('utf-8'))
            sys.stdout.flush()
            print '*'
        else: break
    

    client.py

    import time
    for a in xrange(3):
        time.sleep(a)
        print a
    

    OUT:

    0*
    *
    
    *
    1*
    *
    
    *
    2*
    *
    
    *
    
    0 讨论(0)
提交回复
热议问题