running multiple bash commands with subprocess

后端 未结 5 1876
盖世英雄少女心
盖世英雄少女心 2020-11-27 12:22

If I run echo a; echo b in bash the result will be that both commands are run. However if I use subprocess then the first command is run, printing out the whole

5条回答
  •  伪装坚强ぢ
    2020-11-27 13:20

    I just stumbled on a situation where I needed to run a bunch of lines of bash code (not separated with semicolons) from within python. In this scenario the proposed solutions do not help. One approach would be to save a file and then run it with Popen, but it wasn't possible in my situation.

    What I ended up doing is something like:

    commands = '''
    echo "a"
    echo "b"
    echo "c"
    echo "d"
    '''
    
    process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    out, err = process.communicate(commands)
    print out
    

    So I first create the child bash process and after I tell it what to execute. This approach removes the limitations of passing the command directly to the Popen constructor.

提交回复
热议问题