2

I'm trying to execute a shell script from python and also capture the output.

I'm using the following lines:

x = subprocess.run(["sh", "/path/to/script/myscript.bash"], stdout=subprocess.PIPE)
print(x.stdout.decode('utf8'))

This works fine when running in python interactive mode, but it just hangs when executed inside a python script and I have to use ctrl+Z to kill the python script. What am I missing?

In the past with python 2.7 I had just used a line like:

x = subprocess.Popen(args='sh /path/to/script/myscript.bash', stdout=subprocess.PIPE, shell=True) 
scriptOutput = str(x.communicate()[0])

This doesn't seem to work with python 3.6 which is what I'm running.

Dr.Tautology
  • 416
  • 1
  • 8
  • 19
  • Does this answer your question? [Retrieving the output of subprocess.call()](https://stackoverflow.com/questions/1996518/retrieving-the-output-of-subprocess-call) – de_classified Apr 02 '20 at 15:33
  • Not really. My main issue right now isn't even capturing the output, it's the fact that the command won't execute when run from a python script. – Dr.Tautology Apr 02 '20 at 15:36
  • 1
    what's the traceback. – de_classified Apr 02 '20 at 15:37
  • How can I get a stack trace if the application is hanging and has to be killed? – Dr.Tautology Apr 02 '20 at 17:24
  • add some debug to see where it's faulting, is this all the code in the script or is there more? – de_classified Apr 02 '20 at 17:50
  • Insufficient information. What does *myscript.bash* do? Does it read from stdin? Also, why invoke `sh` explicitly? Your script should have a proper `#!` line (e.g., `#!/bin/sh`) in which case you can just execute it directly. When tackling a problem like this a useful strategy is to simplify the problem. For example, instead of executing your script try running `subprocss.run(['sh', '-c', 'echo hello'])`. If that works it means there is something about your script that is the problem. If it doesn't your python code is wrong. – Kurtis Rader Apr 02 '20 at 22:31
  • @KurtisRader The shebang is only used if the script has execute permissions; neither is necessary to actually execute the script. `['sh', ...]` is fine (assuming the script is, in fact, written to the POSIX specification; otherwise, `['bash', ...]` should be used). – chepner Apr 04 '20 at 00:32
  • @chepner, I know that (I've been using UNIX for 35 years). It's simply more idiomatic and when I see 'sh /path/to/script' it's a red flag the person may not know what they're doing. – Kurtis Rader Apr 05 '20 at 01:10

0 Answers0