Python中的命令行输入 [英] Command line input in Python

查看:140
本文介绍了Python中的命令行输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to run first the program then wait for the input of the user in command line. e.g.

Run...

Process...

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

Process...


推荐答案

目前尚不清楚OP的含义(即使在评论中前后反复),但这是对以下可能解释的两个答案问题:

It is not at all clear what the OP meant (even after some back-and-forth in the comments), but here are two answers to possible interpretations of the question:

使用<$ c $在Python 2.x中为c> raw_input ,在Python 3中为 input 。(这些都是内置的,因此您无需导入任何内容使用它们;您只需要为您的python版本使用正确的一个即可。)

Use raw_input in Python 2.x, and input in Python 3. (These are built in, so you don't need to import anything to use them; you just have to use the right one for your version of python.)

例如:

user_input = raw_input("Some input please: ")

更多详细信息可以在此处找到。

More details can be found here.

例如,您可能有一张纸条看起来像这样

So, for example, you might have a script that looks like this

# 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)

如果您将其保存在 foo.py ,您可以只从命令行调用脚本,它会打印出 tok tiktok ,然后要求您输入。您可以输入 bar baz (然后按回车键),它会打印 bar baz 。这看起来像:

If you saved this in foo.py, you could just call the script from the command line, it would print out tok tiktok, then ask you for input. You could enter bar baz (followed by the enter key) and it would print bar baz. Here's what that would look like:

$ python foo.py
tok tiktok
Some input please: bar baz
bar baz

此处, $ 表示命令行提示符(因此, t实际上是键入该字符),然后在要求输入时键入 bar baz 后按 Enter

Here, $ represents the command-line prompt (so you don't actually type that), and I hit Enter after typing bar baz when it asked for input.

假设您有一个名为 foo.py 的脚本,并想使用参数 bar baz ,例如

Suppose you have a script named foo.py and want to call it with arguments bar and baz from the command line like

$ foo.py bar baz

(再次, $ 表示然后,您可以在脚本中执行以下操作:

(Again, $ represents the command-line prompt.) Then, you can do that with the following in your script:

import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]

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

Here, the variable arg1 will contain the string 'bar', and arg2 will contain 'baz'. The object sys.argv is just a list containing everything from the command line. Note that sys.argv[0] is the name of the script. And if, for example, you just want a single list of all the arguments, you would use sys.argv[1:].

这篇关于Python中的命令行输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆