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)
2 Answers 2
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.
1 Comment
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
5 Comments
i is commonly used as a numeric iterator, not a line in a file, while f is a "file object". Variable names aren't too important otherwise, but list is a builtin Python type, so you wouldn't have been able to use the list() function otherwise. I moved the [0] so you could also access the other values of the output, if needed. Regarding the final line, I'm not using %s here, but I don't think that should happen
pythonquestions, where indentation matters.racadm_command % isupposed to do that isn't already done?% iis needed afterracadm_command.listor any other Python data type