0

I'm trying to capture the output of a bash line I'm executing in my python script using the following code:

call_bash = subprocess.Popen(['/space/jazz/1/users/gwarner/test.sh'],stdout=subprocess.PIPE)
output = call_bash.communicate()[0]

This works fine but I'd like to change it so that that bash code is written directly into this python script (eliminating the need for a separate .sh file). I know that I can run bash code from python with subprocess.call() but I can't figure out how to capture the output (what normally gets printed to the terminal incase I'm using the wrong terminology). Can anyone help?

I'm running python 2.7 on CentOS

7
  • Whats your bash file look like? How can we help merge the shell script into a python script if we don't know what it is? Commented Aug 6, 2015 at 15:16
  • @heinst i think he is asking for general solution. op wants to embed bash script in python script directly, while execute it as a bash script alone Commented Aug 6, 2015 at 15:18
  • @heinst ssh [email protected] scp me#comp:/~/blah.text ep#comp:/register/ This is the script though the answer should be the same regardless of what it is. I'm asking about executing bash code in python and retrieving it's output. Commented Aug 6, 2015 at 15:21
  • @GWarner with my tests, if you do print output it should contain the output of the shell script Commented Aug 6, 2015 at 15:24
  • @heinst Yes, but what I'm asking is how do I change this code so that that actual bash code is in the python script as opposed to a seperate .sh file. I'm looking for something like: call_bash = subprocess.Popen(['ssh [email protected] scp me#comp:/~/blah.text ep#comp:/register/'],stdout=subprocess.PIPE) output = call_bash.communicate()[0] print output Commented Aug 6, 2015 at 15:27

1 Answer 1

2

The first argument to subprocess.Popen is a list of arguments (unless you specify shell=True).

So you could do your example like

call_bash = subprocess.Popen(['ssh', '[email protected]', 'scp me#comp:/~/blah.text ep#comp:/register/'], stdout=subprocess.PIPE)
output = call_bash.communicate()[0]

This will invoke the ssh command with 2 arguments, [email protected] and scp me#comp:/~/blah.text ep#comp:/register/.

Sign up to request clarification or add additional context in comments.

1 Comment

They asked how to run that command without using an external script, what part of my answer does not satisfy that question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.