Question

Actually i am trying to pass below code to the bash. But i think %s of tshark and pythonic %s are mixing somehow. It gives not enough argument format string error.

 def traffic_dest_port(self,filepcap):
    cmd = "tshark -o column.format:'\"Source\", \"%s\", \"Destination\", \"%d\", \"dstport\", \"%uD\"' -r %s |sort|uniq " %filepcap
    subprocess.call(cmd,shell=True)

Can you help me out on this?

Thanks.

Was it helpful?

Solution

You are right in your guess. Python's % operator will try to replace every % specifier in the string, not just some of them. Since it finds 4 % specifiers, and only one value, it will say TypeError: not enough arguments for format string.

But, even if it didn't, how did you expect it to guess which one you wanted it to replace out of those four? I'm a human, and even I'm having trouble guessing, so if I guessed wrong, hopefully you can figure out how to adjust the answer to fit your needs.


One way around this is to escape the percents you don't want Python to process by doubling them:

cmd = "tshark -o column.format:'\"Source\", \"%%s\", \"Destination\", \"%%d\", \"dstport\", \"%%uD\"' -r %s |sort|uniq " %filepcap

As described in the documentation on printf-style String Formatting, the specifier %% means "No argument is converted, results in a '%' character in the result."

And if you print out the result (which you always should when trying to debug stuff like this!), you'll see that the %s has been replaced by the filepcap value, but the %%s has turned into %s.


However, a much easier solution is to just use a different formatting mechanism that doesn't require %, like str.format:

cmd = "tshark -o column.format:'\"Source\", \"%s\", \"Destination\", \"%d\", \"dstport\", \"%uD\"' -r {} |sort|uniq ".format(filepcap)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top