Exemple #1
0
def run_subprocess():
    # Create the continuous terminal process
    if Shell.is_windows():
        proc = Popen('cmd.exe',
                     stdin=PIPE,
                     stdout=PIPE,
                     stderr=PIPE,
                     shell=False)
    else:
        proc = Popen('/bin/bash',
                     stdin=PIPE,
                     stdout=PIPE,
                     stderr=PIPE,
                     shell=False)

    # Cannot communicate multiple times
    # out, err = proc.communicate(input=b'cd ./storage\n')
    # print(out, err, proc.poll())
    # out, err = proc.communicate(input=b'dir\n')
    # print(out, err)

    proc.stdin.write(b'cd ./storage\n')
    proc.stdin.flush()
    print(proc.poll(), proc.returncode)
    proc.stdin.write(b'dir\n')
    proc.stdin.flush()
    print(proc.poll(), proc.returncode)
Exemple #2
0
def run_manual():
    import io
    import sys
    from shell_proc import Shell

    # Initialize and run tasks
    sh = Shell('mkdir storage',
               'cd storage',
               'echo Hello World! > hello.txt',
               stderr=io.StringIO())

    # Manually run tasks
    if sh.is_windows():
        sh('python -m venv ./winvenv')
        sh('call ./winvenv/Scripts/activate.bat')
    else:
        pwd = sh('pwd')
        sh('cd ~')
        sh('python3 -m venv ./lxvenv')
        sh('source ./lxvenv/bin/activate')
        sh('cd {}'.format(pwd.stdout))

    # Not exactly success. If True no output was printed to stderr. Stderr could also be warning like need to update pip
    results = sh.run('pip install requests')
    print("***** Successful install: ", results.exit_code == 0)
    if results.exit_code != 0:
        sh.stderr.seek(0)  # Move to start of io.StringIO()
        err = sh.stderr.read()  # All text collected into stderr from subprocess stderr
        print(err, file=sys.stderr)
        # sh.print_stderr()  # Also available

    sh.stdout = io.StringIO()  # Start saving output for new tasks
    results = sh('pip list')
    print('***** Output Printed\n', results.stdout)

    sh('pip -V')
    print('pip -V =>', sh.last_command.stdout)  # ... for some odd reason PyCharm terminal does not print this "\r\r\n"

    print('All collected stdout')
    sh.stdout.seek(0)  # Move to start of io.StringIO()
    print(sh.stdout.read(), end='', flush=True)  # Print all read data

    # Should close when finished to stop threads from reading stdout and stderr subprocess.PIPE
    # (will close automatically eventually)
    sh.close()