user2639990
user2639990

Reputation:

Error while deciphering a string

Any inputs on what is wrong with line phCmd = "ph %s return all".split(' ') % (qgroup) ? I am trying to decipher the string %s.

from subprocess import Popen, PIPE, STDOUT

def main ():
    qgroups = ['tech.sw.list','tech.sw.amss']
    for qgroup in qgroups:
        print qgroup
        phCmd = "ph %s return all".split(' ') % (qgroup)
        phPipe = Popen(phCmd, stdout=PIPE, stderr=PIPE)
        (output, error) = phPipe.communicate()
        print output
        if phPipe.returncode != 0:
            print output
            raise IOError, "phcommand %s failed" % (phCmd)
        return output

ERROR:

Traceback (most recent call last):
  File "test.py", line 20, in <module>
    main()
  File "test.py", line 9, in main
    phCmd = "ph %s return all".split(' ') % (qgroup)
if __name__ == '__main__':
    main()

Upvotes: 0

Views: 94

Answers (3)

user2555451
user2555451

Reputation:

When using "%" with strings, you have to place it right after the string. This line of code

phCmd = "ph %s return all".split(' ') % (qgroup)

is actually telling Python to take the list returned by "ph %s return all".split(' ') and run an operation similar to:

>>> 2 % 2
0
>>>

on it using (qgroup), which blows up. To fix your problem, do this:

phCmd = ("ph %s return all" % qgroup).split(' ')

Upvotes: 2

miikkas
miikkas

Reputation: 818

The .split(' ') method call of a string returns a list. Try something like

phCmd = ("ph %s return all" % (qgroup)).split(' ')

instead.

Upvotes: 3

arshajii
arshajii

Reputation: 129537

"ph %s return all".split(' ') % (qgroup)

The split() call returns a list, and % is undefined for the argument types list and tuple. I'm not sure what you mean to do here, but it looks like you want:

("ph %s return all" % (qgroup)).split(' ') 

Upvotes: 2

Related Questions