Reputation: 11669
I am exuecuting shell script from my Python script -
import subprocess
proc = subprocess.Popen('#!/bin/bash\n\nulimit -n 8092\n\nulimit -a\n', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable='/bin/bash')
(stdout, stderr) = proc.communicate()
if proc.returncode != 0:
print "Hello, ABC! " % stderr;
sleep(0.05) # delay for 50 ms
else:
print "Hello, FGH! " % stdout;
But it is always giving me error message as -
Traceback (most recent call last):
File "test_python_1.sh", line 8, in <module>
print "Hello, FGH! " % stdout;
TypeError: not all arguments converted during string formatting
Anything wrong I am doing?
Upvotes: 0
Views: 858
Reputation: 365707
What you're doing wrong is misusing the string formatting operator.
The idea behind my_string % my_values
is that Python goes through my_string
looking for format specifiers, starting with a %
character, and replacing them with the values from my_values
. So, when you do this:
"Hello, FGH! %s" % stdout
… the %s
will be replaced with the value of stdout
. And similarly, if you do this:
"Hello, ABC! %s\nHello, FGH! %n" % (stderr, stdout)
… the first %s
will be replaced with stderr
and the second one with stdout
. But when you do this:
"Hello, FGH " % stdout
… there is no %s
, or any other format specifier, to be replaced by stdout
. That's why it's complaining "not all arguments converted during string formatting": you have one argument, stdout
, but zero of your arguments were "converted" by format specifiers, so there's one left over.
So, if you want the value of stdout
to appear after the space, you need to put a %s
after the space:
"Hello, FGH %s" % stdout
However, as Padraic Cunningham points out, you don't even really need that here. You're using a print
statement, and print
can take multiple arguments and print them out with spaces between. So, all you need is:
print "Hello, FGH", stdout
(If/when you later go to Python 3.x, you will need to add parentheses around the arguments, because print
is a normal function instead of a special kind of statement. But otherwise, this still works.)
Upvotes: 1