简体   繁体   English

如何在python中从原始输入创建多个变量?

[英]How do you create multiple variables from raw input in python?

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. 因此,如果他们输入HOST1,HOST2,HOST3,则脚本将为每个条目运行命令。 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. 如果用户键入3个主机名,则myhostbecomesvariables使用3个参数。 If they had typed 5 host names then it would have 5 arguments. 如果他们输入了5个主机名,那么它将有5个参数。

raw_input returns a single string. raw_input返回单个字符串。 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: 或拆分为2行:

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

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. 实际上没有必要在这里将主机解压缩成组成部分 - 因为(我假设)你将为每个主机执行相同的操作,只需在循环中执行。

It certainly depends on your use case, but using the shlex Python module handles raw shell input well such as quoted values. 它当然取决于您的用例,但使用shlex Python模块可以很好地处理原始shell输入,例如引用值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM