Smith
Smith

Reputation: 21

Error with python string formatting

I am working on a script that takes a text file containing IP addresses (one per line) and then passes each IP into a non-Python program command.

The result is an error:

TypeError: not all arguments converted during string formatting

import subprocess
list='c:\cmc_list.txt'

with open(list,'r') as cmc_list:

for i in cmc_list:
  racadm_command = "racadm -r %s -u root -p calvin getslotname" % i

output = subprocess.Popen(racadm_command % i, stdout = subprocess.PIPE, 
 shell=True).communicate()[0]

print(racadm_command, output)

Upvotes: 1

Views: 345

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 192033

I believe you meant to do the formatting only once

import subprocess
cmc_list='c:\cmc_list.txt'

racadm_command_template = "racadm -r {} -u root -p calvin getslotname"

with open(cmc_list,'r') as f:
    for ip in f:
        cmd = racadm_command_template.format(ip)
        output = subprocess.Popen(cmd, stdout = subprocess.PIPE, shell=True).communicate()

        print(cmd, output[0])

I also suggest using getpass for your password prompt, or import from an environment variable. Additionally, don't print out the password and please change it from the default

Upvotes: 0

stolenmoment
stolenmoment

Reputation: 443

The string passed to the Popen command has already been formatted, so it has no % left to consume the i. Take away the "% i" and I think you'll be fine.

Upvotes: 1

Related Questions