python - Sending multiple commands to a bash shell which must share an environment -


I'm trying to follow this reply:

I have more than one command command Needing to execute the same environment is my test case simple:

  import subprocess CMD = subprocess. Popen (['bash'], staden = subprances .ppe, stadout = subprances .ppe) # First command command = Export greet = hello \ n "cmd.stdin.write (command) cmd.stdin.flush () # To do that the data should be shipped in the hair result results = cmd.stdout.read () print result #, type the second command command = "echo $ greeting world \ n" cmd.stdin.write (command) cmd.stdin .flush () # Make sure that the data results in the hair process = cmd.stdout.read () print result   

let me know which Hopefully (on the basis of the referenced answer) it is that "Hello world" has been printed. What really happens is that it is hanging on the first cmd.stdout.read () , and never

Why can anyone explain cmd.stdout.read () never returns?

Notes:

  • It is absolutely essential that I run many boot commands from Python in the same environment. Thus, subprocess.communicate () does not help because it ends Waits to process.
  • Note that in the case of my real test, there is not a stable list of bash commands to execute it. Logic is more dynamic I do not have the option of running them all at once.

    You have two problems here:

    1. If your first order does not produce any output then waiting for some people reading before.
    2. You are using () Read (instead of Readline) - Read () will be blocked until there is enough data available.

      The following modified code (updated with the voting suggestion of Martjen) works fine:

        select import sub-import import cmd = Subprances Popen (['bash'], stdin = subprocess.PIPE, stdout = subprocess .PIPE) poll = select.poll () poll.register (cmd.stdout.fileno (), select.POLLIN) # command command = "export Hello = Hello \ n "cmd.stdin.write (command) cmd write .stdin.flush () # To ensure this, it is necessary to ensure that the hair process is ready = poll.poll (500) if ready: Results = cmd.stdout.readline () Print Result # Type the second command = "echo $ best wishes to the world \ n" cmd.stdin.write (command) cmd.stdin.flush () # To ensure that the hair process Ready = poll.poll ( 500) has been prepared, it is necessary to ensure: Results = cmd.stdout.readline () Print result   

      Up to 500ms is over - adjust your needs.

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -