Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save scythargon/34d39ca5f182c2d6194a to your computer and use it in GitHub Desktop.
Save scythargon/34d39ca5f182c2d6194a to your computer and use it in GitHub Desktop.

Revisions

  1. scythargon revised this gist May 29, 2015. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions python3 subprocess stdin stdout communication
    Original file line number Diff line number Diff line change
    @@ -24,7 +24,7 @@ for line in sys.stdin:
    ## multiple children example
    #####

    #!/usr/bin/pyrhon3
    #!/usr/bin/python3
    # parent.py
    import sys
    import time
    @@ -51,7 +51,7 @@ while children:



    #!/usr/bin/pyrhon3
    #!/usr/bin/python3
    # child.py
    import time
    import sys
  2. scythargon revised this gist May 29, 2015. 1 changed file with 44 additions and 0 deletions.
    44 changes: 44 additions & 0 deletions python3 subprocess stdin stdout communication
    Original file line number Diff line number Diff line change
    @@ -18,3 +18,47 @@ import sys
    for line in sys.stdin:
    line = line.rstrip('\n')
    print(line.upper(), flush=True)


    #####
    ## multiple children example
    #####

    #!/usr/bin/pyrhon3
    # parent.py
    import sys
    import time
    from subprocess import Popen, PIPE

    children = []

    for i in range(5):
    p = Popen([sys.executable, "child.py", "%s" % i], stdout=PIPE, stdin=PIPE, bufsize=1,
    universal_newlines=True)
    children.append(p)

    while children:
    for child in children:
    while child.poll() is None:
    line = child.stdout.readline().rstrip('\n')
    if line == "over" or not line:
    break
    print(line, flush=True)
    if child.poll() is not None:
    children.remove(child)

    time.sleep(0.1)



    #!/usr/bin/pyrhon3
    # child.py
    import time
    import sys

    num = sys.argv[1]

    for i in range(3):
    print("Children %s: %s" % (num, i), flush=True)
    print("over", flush=True)
    time.sleep(0.5)
  3. scythargon created this gist May 29, 2015.
    20 changes: 20 additions & 0 deletions python3 subprocess stdin stdout communication
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    #!/usr/bin/python3
    # parent.py
    import sys
    from subprocess import Popen, PIPE

    with Popen([sys.executable, "child.py"], stdout=PIPE, stdin=PIPE, bufsize=1,
    universal_newlines=True) as p:
    for line in sys.stdin:
    line = line.rstrip('\n')
    print(line, file=p.stdin, flush=True)
    print(p.stdout.readline().rstrip('\n'), flush=True)


    #!/usr/bin/python3
    # child.py
    import sys

    for line in sys.stdin:
    line = line.rstrip('\n')
    print(line.upper(), flush=True)