2013-10-15 41 views
-3

我想編寫一個響應命令行輸入的程序。如何編寫一個響應命令行輸入的程序?

c:\>python my_responder.py 

然後它將給我一個提示:通常情況下,我會在命令行啓動程序

responder> Hello. Please type your question. 
responder> _ 

然後我會輸入一些東西,然後按Enter:

responder> How many days are there in one week? 

響應者將回復一個函數的結果(其輸入是輸入的字符串)。例如

def respond_to_input(input): 
    return 'You said: "{}". Please type something else.'.format(input) 

responder> You said: "How many days are there in one week?". Please type something else. 

我似乎無法將這種命令行輸入/輸出連接到python中的函數。

附加信息:我不理解標準輸入/標準輸出,他們覺得相關。我一般也不瞭解如何讓Python與命令行進行交互(除了運行一個可以打印到窗口的python程序)。

+0

http://www.tutorialspoint.com/py thon/python_command_line_arguments.htm – dmp

+2

你應該使用'raw_input(「請輸入輸入:」)'你想得到你的輸入。 –

+0

「我似乎無法將這種命令行輸入/輸出連接到python中的函數。」 - 因爲你沒有做研究而被標記爲脫離主題。只是使用'python input'搜索會導致你多個資源,這將全部解決你的問題,從[這個問題]開始(http://stackoverflow.com/questions/70797/python-and-user-input) – l4mpi

回答

0
的raw_input從除了

()也有sys.argv列表,(http://docs.python.org/2/tutorial/interpreter.html#argument-passing),這是非常有用的:

from __future__ import print_function # Only needed in python2. 
from sys import argv as cli_args 

def print_cli_args(): 
    print(*cli_args[1:]) 


print_cli_args() 

你將它保存在一個文件中,可以說echo.py並運行它像這在shell:

$ python2 echo.py Hello, World! 

而且,它還將打印到標準輸出:

Hello, World! 
相關問題