Jak monitować o wejście użytkownika i odczyt argumentów wiersza poleceń [zamknięty]

zamknięte . To pytanie musi być bardziej skoncentrowane . Obecnie nie przyjmuje odpowiedzi.

chcesz poprawić to pytanie? Update the question so it edytując ten post.

Zamknięte 1 rok temu .

Popraw to pytanie

Jak mam skrypt Pythona, który a) może akceptować dane wejściowe użytkownika i jak to zrobić b) odczytywać argumenty, jeśli są uruchamiane z linii poleceń?

Author: Georgy, 2008-09-16

12 answers

Aby odczytać dane użytkownika, możesz wypróbować Moduł cmd do łatwego tworzenia mini-interpretera wiersza poleceń (z tekstami pomocy i autocompletion) oraz raw_input (input dla Pythona 3+) do odczytu wiersza tekstu od użytkownika.

text = raw_input("prompt")  # Python 2
text = input("prompt")  # Python 3

Wejścia wiersza poleceń są w sys.argv. Spróbuj tego w swoim skrypcie:

import sys
print (sys.argv)

Istnieją dwa moduły do analizy opcji wiersza poleceń: optparse (deprecated since Python 2.7, use argparse zamiast) I getopt. Jeśli chcesz tylko wprowadzić pliki do swojego skryptu, oto moc fileinput.

The Python library reference jest twoim przyjacielem.

 529
Author: Antti Rasinen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-12 20:02:06
var = raw_input("Please enter something: ")
print "you entered", var

Lub dla Pythona 3:

var = input("Please enter something: ")
print("You entered: " + var)
 472
Author: lbz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-20 11:43:26

raw_input nie jest już dostępny w Pythonie 3.X. ale raw_input została zmieniona na input, więc ta sama funkcjonalność istnieje.

input_var = input("Enter something: ")
print ("you entered " + input_var) 

Dokumentacja zmiany

 203
Author: steampowered,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-26 21:21:42

Najlepszym sposobem przetwarzania argumentów wiersza poleceń jest argparse moduł.

Użyj raw_input(), Aby uzyskać dane wejściowe użytkownika. Jeśli importujesz readline module Twoi użytkownicy będą mieli edycję linii i historię.

 33
Author: Dave Webb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-21 10:15:41

Uważaj, aby nie używać funkcji input, chyba że wiesz, co robisz. W przeciwieństwie do raw_input, input zaakceptuje Dowolne wyrażenie Pythona, więc jest to trochę jak eval

 18
Author: Vhaerun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-08 23:23:42

Ten prosty program pomaga w zrozumieniu, jak podawać dane wejściowe użytkownika z linii poleceń i pokazywać pomoc przy przekazywaniu nieprawidłowego argumentu.

import argparse
import sys

try:
     parser = argparse.ArgumentParser()
     parser.add_argument("square", help="display a square of a given number",
                type=int)
    args = parser.parse_args()

    #print the square of user input from cmd line.
    print args.square**2

    #print all the sys argument passed from cmd line including the program name.
    print sys.argv

    #print the second argument passed from cmd line; Note it starts from ZERO
    print sys.argv[1]
except:
    e = sys.exc_info()[0]
    print e

1) aby znaleźć pierwiastek kwadratowy z 5

C:\Users\Desktop>python -i emp.py 5
25
['emp.py', '5']
5

2) podanie nieprawidłowego argumentu innego niż liczba

C:\Users\bgh37516\Desktop>python -i emp.py five
usage: emp.py [-h] square
emp.py: error: argument square: invalid int value: 'five'
<type 'exceptions.SystemExit'>
 18
Author: Viswesn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-20 05:33:16

Użyj 'raw_input' do wprowadzania danych z konsoli / terminala.

Jeśli chcesz po prostu podać argument linii poleceń, np. nazwę pliku lub coś takiego, np.

$ python my_prog.py file_name.txt

Wtedy możesz użyć sys.argv...

import sys
print sys.argv

Sys.argv jest listą, gdzie 0 jest nazwą programu, więc w powyższym przykładzie sys.argv[1] będzie " nazwa_pliku.txt "

Jeśli chcesz mieć pełne opcje wiersza poleceń użyj modułu optparse.

Pev

 11
Author: Simon Peverett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-16 09:52:24

Jeśli używasz Pythona optparse , który, jak wyjaśnia dokument, utworzy interfejs do argumentów linii poleceń, które są wywoływane podczas uruchamiania aplikacji.

Jednak w Pythonie ≥2.7, optparse został przestarzały i został zastąpiony argparse Jak pokazano powyżej. Szybki przykład z dokumentów...

Poniższy kod jest programem Pythona, który pobiera listę liczb całkowitych i produkuje albo sumę, albo max:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)
 10
Author: Matt Olan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-26 01:53:08

Od Pythona 3.2 2.7, istnieje teraz argparse do przetwarzania argumentów linii poleceń.

 7
Author: GreenMatt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-22 16:43:00

Jeśli to 3.wersja x następnie po prostu użyj:

variantname = input()

Na przykład, chcesz wprowadzić 8:

x = input()
8

X będzie równe 8, ale będzie to ciąg znaków, chyba że zdefiniujesz go inaczej.

Więc możesz użyć polecenia convert, jak:

a = int(x) * 1.1343
print(round(a, 2)) # '9.07'
9.07
 7
Author: CorpseDead,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-22 21:23:08

W Pythonie 2:

data = raw_input('Enter something: ')
print data

W Pythonie 3:

data = input('Enter something: ')
print(data)
 3
Author: Mark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-01 18:39:44
import six

if six.PY2:
    input = raw_input

print(input("What's your name? "))
 2
Author: Will Charlton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-17 17:10:43