Python中的命令行输入

Vii*_*iin 31 python command-line user-input input python-2.7

是否可以先运行程序,然后在命令行中等待用户的输入.例如

Run...

Process...

Input from the user(in command line form)...

Process...
Run Code Online (Sandbox Code Playgroud)

Mik*_*ike 81

OP的含义一点也不清楚(即使在评论中有些来回),但这里有两个可能解释问题的答案:

对于交互式用户输入(或管道命令或重定向输入)

使用raw_input在Python 2.x和input在Python 3(这些都是内置的,所以你不需要输入任何东西来使用它们.你只需要使用适合您Python版本)

例如:

user_input = raw_input("Some input please: ")
Run Code Online (Sandbox Code Playgroud)

更多细节可以在这里找到.

因此,例如,您可能有一个看起来像这样的脚本

# First, do some work, to show -- as requested -- that
# the user input doesn't need to come first.
from __future__ import print_function
var1 = 'tok'
var2 = 'tik'+var1
print(var1, var2)

# Now ask for input
user_input = raw_input("Some input please: ") # or `input("Some...` in python 3

# Now do something with the above
print(user_input)
Run Code Online (Sandbox Code Playgroud)

如果你保存了这个foo.py,你可以从命令行调用脚本,它会打印出来tok tiktok,然后请你输入.您可以输入bar baz(后跟输入键),然后打印bar baz.这是什么样子:

$ python foo.py
tok tiktok
Some input please: bar baz
bar baz
Run Code Online (Sandbox Code Playgroud)

这里,$代表命令行提示符(所以你实际上并没有输入),当我要求Enter输入bar baz时我打字后点击.

对于命令行参数

假设您有一个名为的脚本,foo.py并希望使用参数barbaz命令行调用它

$ foo.py bar baz
Run Code Online (Sandbox Code Playgroud)

(再次,$表示命令行提示符.)然后,您可以在脚本中执行以下操作:

import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]
Run Code Online (Sandbox Code Playgroud)

这里,变量arg1将包含字符串'bar',arg2并将包含'baz'.该对象sys.argv只是一个包含命令行中所有内容的列表.请注意,这sys.argv[0]是脚本的名称.例如,如果您只想要所有参数的单个列表,那么您将使用sys.argv[1:].


Mr_*_*ock 13

只是输入

the_input = raw_input("Enter input: ")
Run Code Online (Sandbox Code Playgroud)

就是这样.

此外,如果您想要制作输入列表,您可以执行以下操作:

a = []

for x in xrange(1,10):
    a.append(raw_input("Enter Data: "))
Run Code Online (Sandbox Code Playgroud)

在这种情况下,系统会要求您提供10次数据,以便在列表中存储9个项目.

输出:

Enter data: 2
Enter data: 3
Enter data: 4
Enter data: 5
Enter data: 7
Enter data: 3
Enter data: 8
Enter data: 22
Enter data: 5
>>> a
['2', '3', '4', '5', '7', '3', '8', '22', '5']
Run Code Online (Sandbox Code Playgroud)

您可以使用类似的内容(在制作该列表之后)搜索该列表的基本方式:

if '2' in a:
    print "Found"
Run Code Online (Sandbox Code Playgroud)

否则:打印"未找到".

您可以将"2"替换为"raw_input()",如下所示:

if raw_input("Search for: ") in a:
    print "Found"
else: 
    print "Not found"
Run Code Online (Sandbox Code Playgroud)

通过命令行界面从输入文件中获取原始数据

如果你想从你通过命令行输入的文件中获取输入(这通常是你在竞争时遇到代码问题所需要的,比如Google Code Jam或ACM/IBM ICPC):

example.py

while(True):
    line = raw_input()
    print "input data: %s" % line
Run Code Online (Sandbox Code Playgroud)

在命令行界面:

example.py < input.txt
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.


小智 10

如果您使用的是Python 3,raw_input则已更改为input

Python 3示例:

line = input('Enter a sentence:')
Run Code Online (Sandbox Code Playgroud)