명령 줄 인수를 읽고 처리하는 방법은 무엇입니까?
저는 원래 C 프로그래머입니다. 나는 다양한 논증을 읽기위한 수많은 트릭과 "핵"을 보았다.
파이썬 프로그래머가 이것을 할 수있는 방법은 무엇입니까?
관련
- Python 스크립트에 전달 된 명령 줄 인수를 가져오고 구문 분석하는 가장 좋은 방법은 무엇입니까?
- "[command] [action] [parameter]"스타일 명령 줄 인터페이스 구현?
- Python에서 명령 줄 인수를 어떻게 처리 할 수 있습니까?
- Python의 optparse를 사용하여 위치 인수 도움말을 어떻게 포맷합니까?
표준 라이브러리의 표준 솔루션은 argparse
( docs ) :
다음은 예입니다.
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
args = parser.parse_args()
argparse
지원 (특히) :
- 순서에 관계없이 여러 옵션.
- 단기 및 장기 옵션.
- 기본값입니다.
- 사용 도움말 메시지 생성.
import sys
print("\n".join(sys.argv))
sys.argv
명령 줄에서 스크립트에 전달 된 모든 인수가 포함 된 목록입니다.
원래,
import sys
print(sys.argv[1:])
이러한 이유로 더 나은 argparse 를 위해 복음화하기 만하면 됩니다. 본질적으로 :
(링크에서 복사)
argparse 모듈은 위치 및 선택적 인수를 처리 할 수 있지만 optparse는 선택적 인수 만 처리 할 수 있습니다.
argparse는 명령 줄 인터페이스의 모양에 대해 독단적이지 않습니다. -file 또는 / file과 같은 옵션이 지원되며 필수 옵션이 지원됩니다. Optparse는 이러한 기능을 지원하지 않고 실용성보다 순수성을 선호합니다.
argparse는 인수에서 결정된 명령 줄 사용법과 위치 및 선택적 인수 모두에 대한 도움말 메시지를 포함하여 더 많은 정보를 제공하는 사용법 메시지를 생성합니다. optparse 모듈은 사용자가 직접 사용 문자열을 작성해야하며 위치 인수에 대한 도움말을 표시 할 방법이 없습니다.
argparse는 다양한 수의 명령 줄 인수를 사용하는 작업을 지원하는 반면 optparse에서는 정확한 인수 수 (예 : 1, 2 또는 3)를 미리 알고 있어야합니다.
argparse는 하위 명령으로 전달하는 파서를 지원하지만 optparse는
allow_interspersed_args
수동으로 파서 전달을 설정 하고 수행해야합니다.
그리고 개인적으로 좋아하는 것 :
- argparse를 사용하면 유형 및 작업 매개 변수를
add_argument()
간단한 콜러 블로 지정할 수 있으며 optparse는 적절한 인수 검사를STORE_ACTIONS
받거나 같은 클래스 속성을 해킹해야합니다.CHECK_METHODS
또한이 argparse
다음 stdlib 모듈 (다음 stdlib의에서 "impovement" optparse
모듈). argparse 소개의 예 :
# script.py
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'integers', metavar='int', type=int, choices=range(10),
nargs='+', help='an integer in the range 0..9')
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))
용법:
$ script.py 1 2 3 4
4
$ script.py --sum 1 2 3 4
10
One way to do it is using sys.argv
. This will print the script name as the first argument and all the other parameters that you pass to it.
import sys
for arg in sys.argv:
print arg
The docopt library is really slick. It builds an argument dict from the usage string for your app.
Eg from the docopt readme:
"""Naval Fate.
Usage:
naval_fate.py ship new <name>...
naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
naval_fate.py ship shoot <x> <y>
naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
naval_fate.py (-h | --help)
naval_fate.py --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
"""
from docopt import docopt
if __name__ == '__main__':
arguments = docopt(__doc__, version='Naval Fate 2.0')
print(arguments)
If you need something fast and not very flexible
main.py:
import sys
first_name = sys.argv[1]
last_name = sys.argv[2]
print("Hello " + first_name + " " + last_name)
Then run python main.py James Smith
to produce the following output:
Hello James Smith
#set default args as -h , if no args:
if len(sys.argv) == 1: sys.argv[1:] = ["-h"]
I use optparse myself, but really like the direction Simon Willison is taking with his recently introduced optfunc library. It works by:
"introspecting a function definition (including its arguments and their default values) and using that to construct a command line argument parser."
So, for example, this function definition:
def geocode(s, api_key='', geocoder='google', list_geocoders=False):
is turned into this optparse help text:
Options:
-h, --help show this help message and exit
-l, --list-geocoders
-a API_KEY, --api-key=API_KEY
-g GEOCODER, --geocoder=GEOCODER
I like getopt from stdlib, eg:
try:
opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err:
usage(err)
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
if len(args) != 1:
usage("specify thing...")
Lately I have been wrapping something similiar to this to make things less verbose (eg; making "-h" implicit).
As you can see optparse "The optparse module is deprecated with and will not be developed further; development will continue with the argparse module."
Pocoo's click is more intuitive, requires less boilerplate, and is at least as powerful as argparse.
The only weakness I've encountered so far is that you can't do much customization to help pages, but that usually isn't a requirement and docopt seems like the clear choice when it is.
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))
Assuming the Python code above is saved into a file called prog.py
$ python prog.py -h
Ref-link: https://docs.python.org/3.3/library/argparse.html
You may be interested in a little Python module I wrote to make handling of command line arguments even easier (open source and free to use) - Commando
I recommend looking at docopt as a simple alternative to these others.
docopt is a new project that works by parsing your --help usage message rather than requiring you to implement everything yourself. You just have to put your usage message in the POSIX format.
Yet another option is argh. It builds on argparse, and lets you write things like:
import argh
# declaring:
def echo(text):
"Returns given word as is."
return text
def greet(name, greeting='Hello'):
"Greets the user with given name. The greeting is customizable."
return greeting + ', ' + name
# assembling:
parser = argh.ArghParser()
parser.add_commands([echo, greet])
# dispatching:
if __name__ == '__main__':
parser.dispatch()
It will automatically generate help and so on, and you can use decorators to provide extra guidance on how the arg-parsing should work.
My solution is entrypoint2. Example:
from entrypoint2 import entrypoint
@entrypoint
def add(file, quiet=True):
''' This function writes report.
:param file: write report to FILE
:param quiet: don't print status messages to stdout
'''
print file,quiet
help text:
usage: report.py [-h] [-q] [--debug] file
This function writes report.
positional arguments:
file write report to FILE
optional arguments:
-h, --help show this help message and exit
-q, --quiet don't print status messages to stdout
--debug set logging level to DEBUG
참고URL : https://stackoverflow.com/questions/1009860/how-to-read-process-command-line-arguments
'program tip' 카테고리의 다른 글
대신 아이콘에 태그를 (0) | 2020.10.04 |
---|---|
Bash 스크립트에서 스크립트 파일 이름을 어떻게 알 수 있습니까? (0) | 2020.10.04 |
먼저 닫아야하는이 명령과 연결된 열린 DataReader가 이미 있습니다. (0) | 2020.10.03 |
Android 애플리케이션에서 인터넷에 액세스하려면 어떤 권한이 필요합니까? (0) | 2020.10.03 |
JSON과 유사한 형식으로 원형 구조를 인쇄하려면 어떻게해야합니까? (0) | 2020.10.03 |