1

Beginner with python here. I've been doing some online tutorials and can't seem to find the solution to this question. What I'd like to do is this:

hostname = raw_input("Type host name here: ")

Then the user inputs as many host names as they like, type done, then what they entered becomes variables for use in the script. So if they typed HOST1, HOST2, HOST3, done then the script would run commands for each entry. Example:

def myhostsbecomevariables(*args):
      arg1, arg2, arg3, etc etc etc = args
      print "arg1: %r, arg2: %r, etc: %r, etc: %r" % (arg1, arg2, etc etc)

myhostsbecomevariables(HOST1, HOST2, HOST3)

If the user types in 3 host names then myhostbecomesvariables uses 3 arguments. If they had typed 5 host names then it would have 5 arguments.

1
  • I find that expecting the values to be comma separated for something that is entered manually through raw_input is a very bad thing to do. You should either loop in raw_input to read as many times as you need, or you should stop using raw_input and read from somewhere else that is already in the expected format. Commented Jan 21, 2013 at 18:08

2 Answers 2

4

raw_input returns a single string. You can split that string on a delimiter if you wish:

hosts = raw_input("enter hosts (separated by a comma):").split(',')

Or split onto 2 lines:

host_string = raw_input("enter hosts (separated by a comma):")
hosts = hosts_string.split(',')

And you could pass this to myhostbecomevariables using argument unpacking:

myhostbecomevariables(*hosts)

where your function could be defined like this:

def myhostbecomevariables(*hosts):
    for host in hosts:
        print(host)

There really is no need to unpack the hosts into constituent parts here -- Since (I assume) you'll be performing the same action for each host, just do it in a loop.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much. How would I then define myhostbecomevariables?
@mistermister -- I've updated a little. I'm not 100% sure what you're going for here, but hopefully the update will help a little.
Ultimately I would have a script that asks a series of questions, and the answers are put into separate new text files like: "This is my test file. I am %s and I like to eat %s and travel to %s and my favorite color is %s."% (myhostbecomevariables, food, travel, favcolor)
0

It certainly depends on your use case, but using the shlex Python module handles raw shell input well such as quoted values.

import shlex
input = raw_input("Type host name here: ")
hostnames = shlex.split(input)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.