1

I've got a list of hosts that I'm trying to iterate over for a ssh connection. In ruby I can use #{variable} to access a the variable within a command, what should I be doing for python?

I've included the ruby syntax in the following python code as a placeholder of where I'd like the functionality. What is the pythonic way of doing this?

h = """
foo-pants-linux-001
foo-pants-linux-002
foo-pants-linux-003
foo-pants-linux-004
foo-pants-linux-005
"""

hosts = h.split()

for host in hosts:
    subprocess.check_output("ssh foobar@#{host} `echo hi!`")
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Possible duplicate of [Is there a Python equivalent to Ruby's string interpolation?](http://stackoverflow.com/questions/4450592/is-there-a-python-equivalent-to-rubys-string-interpolation) – Moon Cheesez Feb 01 '17 at 23:18
  • If your `h` is going to be multiple lines rather than just whitespace separated, `h.splitlines()` is a more explicit/safer (if you wanted to add an argument along-side the host name, perhaps) way to chop it up. – Nick T Feb 01 '17 at 23:19

1 Answers1

1

You can either use modulo (%) or .format(..):

subprocess.check_output("ssh foobar@%s `echo hi!`"%host)
subprocess.check_output("ssh foobar@{host} `echo hi!`".format(host=host))
subprocess.check_output("ssh foobar@{} `echo hi!`".format(host))

The %s is a format specifier meaning you take the string value of host.

In case you want to introduce multiple named variables you can use {host} and then call format() with the parameter explicitly named.

You can also use {} which means you take the next element in the arguments given to .format(..).

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555