0

I would like to change the standard output from a terminal to a string. I could use the instruction by Frédéric Hamidi in the web page: python: get the print output in an exec statement , and it works. However, if I would like to run ping command, I couldn't reach to specific char in in the string. there is an error which is "IndexError: string index out of range" I would be grateful if you can help me with this problem.

Thanks a lot Anees

The code:

import sys from cStringIO import StringIO import subprocess code2 =""" subprocess.call(['ping','www.google.com','-n','1']) """ old_stdout = sys.stdout redirected_output = sys.stdout = StringIO() exec(code2) sys.stdout = old_stdout x= redirected_output.getvalue() print x print x[10] redirected_output.close() 
3
  • 1
    You're putting python code in a string and then trying to exec it. Use subprocess or exec, not both at once, that makes no sense. Commented Jan 12, 2016 at 1:14
  • What was wrong with just calling subprocess.call(['ping', 'www.google.com', '-n', '1'])? Commented Jan 12, 2016 at 1:42
  • You got len(x) is 0. Commented Jan 12, 2016 at 1:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.