명령줄 인수를 읽고 처리(파스)하려면 어떻게 해야 합니까?
Python에서는 스크립트에 제공된 명령줄 인수를 어떻게 찾아 처리할 수 있습니까?
관련 배경 판독치:"sys.argv[1]"는 무엇을 의미합니까? (sys.argv는 무엇이며, 어디서 왔습니까?)보다 구체적인 예는 "[명령] [action] [parameter]" 스타일의 명령줄 인터페이스 구현을 참조하십시오.Python의 optparse를 사용하는 데 도움이 되는 positional 인수를 포맷하려면 어떻게 해야 합니까?
import sys
print("\n".join(sys.argv))
sys.argv 는 명령줄에서 스크립트에 전달되는 모든 인수를 포함하는 목록입니다. sys.argv[0]을 사용하다
기본적으로는
import sys
print(sys.argv[1:])
은 표준음음음음음음음음음음음음음음 in in in the the in in in the the the the the the the the the the the.argparse(표준):
다음은 예를 제시하겠습니다.
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는 다음을 지원합니다.
- 임의의 순서로 여러 옵션을 사용할 수 있습니다.
- 짧은 옵션과 긴 옵션.
- 디폴트값
- 사용 도움말 메시지 생성
이런 이유로 아르파르세 전도하러 다니는 것 뿐인데..기본적으로 다음과 같습니다.
(링크에서 삭제)
argparse 모듈은 위치 인수와 옵션 인수를 처리할 수 있지만 optparse는 옵션 인수만 처리할 수 있습니다.
argparse는 명령줄 인터페이스가 어떻게 생겼는지에 대해 독단적이지 않습니다.-file 또는 /file과 같은 옵션은 필수 옵션과 마찬가지로 지원됩니다.Optparse는 이러한 기능을 지원하지 않으며, 실용성보다 순수성을 중시합니다.
argparse를 사용하면 인수에 따라 결정된 명령줄 사용방법 및 positional 인수와 optional 인수 모두에 대한 도움말메시지 등 보다 유용한 사용방법 메시지가 생성됩니다.optparse 모듈에서는 사용자 고유의 사용현황 스트링을 써야 하며 positional 인수에 대한 도움말을 표시할 방법이 없습니다.
argparse는 가변 개수의 명령줄 arg를 소비하는 액션을 지원하는 반면 optparse는 정확한 인수 수(1, 2, 또는 3)를 미리 알고 있어야 합니다.
에서는 argparse를 설정해야 .
allow_interspersed_args디스패치를 .
그리고 개인적으로 좋아하는 건
- 및에 argparse를 지정할 수 있습니다.
add_argument()되지만 optparse는 optparse와 같은 로 합니다.STORE_ACTIONS★★★★★★★★★★★★★★★★★」CHECK_METHODS가
stdlib 모듈(stdlib의 '실장')도 있습니다.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
빠르고 유연하지 않은 것이 필요한 경우
main.py:
import sys
first_name = sys.argv[1]
last_name = sys.argv[2]
print("Hello " + first_name + " " + last_name)
다음 " " " " 를 실행합니다.python main.py James Smith
다음 출력을 생성합니다.
안녕하세요 제임스 스미스
으로는 을 사용하는 .sys.argv그러면 스크립트 이름이 첫 번째 인수로 출력되고 스크립트에 전달되는 다른 모든 파라미터가 출력됩니다.
import sys
for arg in sys.argv:
print arg
docopt 라이브러리는 정말 매끄럽다.앱의 사용 문자열에서 인수 dict를 작성합니다.
예를 들어 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)
#set default args as -h , if no args:
if len(sys.argv) == 1: sys.argv[1:] = ["-h"]
저도 옵트파스를 사용하지만 Simon Wilison이 최근에 선보인 옵트 펑크 라이브러리의 방향을 매우 좋아합니다.기능:
"함수 정의(인수 및 기본값 포함)를 검색하고 이를 사용하여 명령줄 인수 파서를 구성합니다.
예를 들어, 이 함수의 정의는 다음과 같습니다.
def geocode(s, api_key='', geocoder='google', list_geocoders=False):
는 다음 optparse 도움말 텍스트로 변환됩니다.
Options:
-h, --help show this help message and exit
-l, --list-geocoders
-a API_KEY, --api-key=API_KEY
-g GEOCODER, --geocoder=GEOCODER
stdlib의 getopt을 좋아합니다.예:
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...")
최근에는 장황하지 않게 하기 위해 이와 비슷한 것을 포장하고 있습니다(예를 들어 "-h"를 암묵적으로 사용).
optparse를 보면 알 수 있듯이 optparse 모듈은 optparse 모듈과 함께 사용되지 않으며 더 이상 개발되지 않습니다. argparse 모듈과 함께 개발이 계속됩니다.
Pocoo의 클릭은 보다 직관적이고 보일러 플레이트가 덜 필요하며 적어도 argparse만큼 강력합니다.
지금까지의 유일한 약점은 도움말 페이지를 커스터마이즈할 수 없다는 것입니다.다만, 보통, 이것은 요건이 아니고, docopt는, 커스터마이즈 할 때 확실한 선택이라고 생각됩니다.
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
당신은 내가 작성한 작은 Python 모듈에 관심이 있을 것이다.명령줄 인수를 더 쉽게 처리할 수 있도록 (오픈 소스 및 무료 사용) - Commando
또 다른 옵션은 argh입니다.argparse를 기반으로 구축되어 다음과 같은 내용을 작성할 수 있습니다.
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()
도움말 등이 자동으로 생성되며, 데코레이터를 사용하여 arg-parsing 동작에 대한 추가 지침을 제공할 수 있습니다.
이러한 방법을 간단하게 대체할 수 있는 방법으로 docopt를 검토할 것을 권장합니다.
docopt는 사용자가 직접 모든 것을 구현하지 않고 --help usage 메시지를 해석함으로써 작동하는 새로운 프로젝트입니다.POSIX 형식으로 사용 메시지를 입력하면 됩니다.
또한 python3에서는 Extended Itable Unpacking을 사용하여 추가 종속성 없이 선택적 위치 인수를 처리할 수 있습니다.
try:
_, arg1, arg2, arg3, *_ = sys.argv + [None] * 2
except ValueError:
print("Not enough arguments", file=sys.stderr) # unhandled exception traceback is meaningful enough also
exit(-1)
상기의argv포장을 풀다arg2그리고.arg3"optional" - 에서 지정되어 있지 않은 경우argv첫 번째가 지정되지 않은 경우 ValueError가 설정됩니다.
Traceback (most recent call last):
File "test.py", line 3, in <module>
_, arg1, arg2, arg3, *_ = sys.argv + [None] * 2
ValueError: not enough values to unpack (expected at least 4, got 3)
import sys
# Command line arguments are stored into sys.argv
# print(sys.argv[1:])
# I used the slice [1:] to print all the elements except the first
# This because the first element of sys.argv is the program name
# So the first argument is sys.argv[1], the second is sys.argv[2] ecc
print("File name: " + sys.argv[0])
print("Arguments:")
for i in sys.argv[1:]:
print(i)
이 파일에 이름을 붙입시다.command_line.py실행해 봅시다.
C:\Users\simone> python command_line.py arg1 arg2 arg3 ecc
File name: command_line.py
Arguments:
arg1
arg2
arg3
ecc
그럼 간단한 프로그램을 만들어 봅시다.sum.py:
import sys
try:
print(sum(map(float, sys.argv[1:])))
except:
print("An error has occurred")
결과:
C:\Users\simone> python sum.py 10 4 6 3
23
제 해결책은 진입점 2입니다.예를 들어:
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
도움말 텍스트:
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
이 기능은 옵션 대체 플래그가 있는 단순한 스위치, 값 스위치를 처리합니다.
import sys
# [IN] argv - array of args
# [IN] switch - switch to seek
# [IN] val - expecting value
# [IN] alt - switch alternative
# returns value or True if val not expected
def parse_cmd(argv,switch,val=None,alt=None):
for idx, x in enumerate(argv):
if x == switch or x == alt:
if val:
if len(argv) > (idx+1):
if not argv[idx+1].startswith('-'):
return argv[idx+1]
else:
return True
//expecting a value for -i
i = parse_cmd(sys.argv[1:],"-i", True, "--input")
//no value needed for -p
p = parse_cmd(sys.argv[1:],"-p")
델의 바이오 테크놀로지 고객 중 몇 명이 최근 다음과 같은 두 가지 질문을 던졌습니다.
- 명령어로 Python 스크립트를 실행하려면 어떻게 해야 합니까?
- Python 스크립트가 명령어로 실행될 때 입력값을 Python 스크립트에 전달하려면 어떻게 해야 합니까?
아래에 Python 스크립트를 첨부했습니다.이 스크립트는 두 가지 질문에 모두 대답할 수 있다고 생각합니다.다음 Python 스크립트가 파일 테스트에 저장되어 있다고 가정해 보겠습니다.py:
#
#----------------------------------------------------------------------
#
# file name: test.py
#
# input values: data - location of data to be processed
# date - date data were delivered for processing
# study - name of the study where data originated
# logs - location where log files should be written
#
# macOS usage:
#
# python3 test.py "/Users/lawrence/data" "20220518" "XYZ123" "/Users/lawrence/logs"
#
# Windows usage:
#
# python test.py "D:\data" "20220518" "XYZ123" "D:\logs"
#
#----------------------------------------------------------------------
#
# import needed modules...
#
import sys
import datetime
def main(argv):
#
# print message that process is starting...
#
print("test process starting at", datetime.datetime.now().strftime("%Y%m%d %H:%M"))
#
# set local values from input values...
#
data = sys.argv[1]
date = sys.argv[2]
study = sys.argv[3]
logs = sys.argv[4]
#
# print input arguments...
#
print("data value is", data)
print("date value is", date)
print("study value is", study)
print("logs value is", logs)
#
# print message that process is ending...
#
print("test process ending at", datetime.datetime.now().strftime("%Y%m%d %H:%M"))
#
# call main() to begin processing...
#
if __name__ == '__main__':
main(sys.argv)
이 스크립트는 다음과 같이 터미널 셸의 MacOS 컴퓨터에서 실행할 수 있으며 결과는 표준 출력으로 인쇄됩니다(현재 디렉터리에 test.py 파일이 포함되어 있는지 확인하십시오).
$ python3 test.py "/Users/lawrence/data" "20220518" "XYZ123" "/Users/lawrence/logs"
test process starting at 20220518 16:51
data value is /Users/lawrence/data
date value is 20220518
study value is XYZ123
logs value is /Users/lawrence/logs
test process ending at 20220518 16:51
이 스크립트는 다음과 같이 Windows 컴퓨터에서 명령 프롬프트로 실행할 수도 있습니다.또한 결과는 표준 출력으로 출력됩니다(현재 디렉토리에 test.py 파일이 포함되어 있는지 확인합니다).
D:\scripts>python test.py "D:\data" "20220518" "XYZ123" "D:\logs"
test process starting at 20220518 17:20
data value is D:\data
date value is 20220518
study value is XYZ123
logs value is D:\logs
test process ending at 20220518 17:20
이 스크립트는 위의 두 가지 질문에 모두 답변하며 입력 값을 가진 명령어로 실행되는 스크립트 개발에 적합한 시작점이 됩니다.
새로운 답변의 이유:
- 기존 답변은 여러 옵션을 지정합니다.
- 표준 옵션은
argparse, 몇 가지 답변은 문서의 예를 제시했고, 한 답변은 그 장점을 제시했습니다.그러나 모두 OP의 실제 질문에 대한 적절한/명확한 답을 설명하지 못했습니다. 적어도 신입사원에게는 그렇습니다.
의 예argparse:
import argparse
def load_config(conf_file):
pass
if __name__ == '__main__':
parser = argparse.ArgumentParser()
//Specifies one argument from the command line
//You can have any number of arguments like this
parser.add_argument("conf_file", help="configuration file for the application")
args = parser.parse_args()
config = load_config(args.conf_file)
위의 프로그램에서는 config 파일이 인수로 필요합니다.당신이 제공해주면, 그것은 행복하게 실행될 것입니다.그렇지 않은 경우 다음 내용이 인쇄됩니다.
usage: test.py [-h] conf_file
test.py: error: the following arguments are required: conf_file
인수가 옵션인지 여부를 지정할 수 있습니다.
다음 명령을 사용하여 인수의 예상 유형을 지정할 수 있습니다.
type열쇠parser.add_argument("age", type=int, help="age of the person")인수의 기본값을 지정하려면
default조작
이 문서는 어느 정도 이해에 도움이 될 것입니다.
언급URL : https://stackoverflow.com/questions/1009860/how-can-i-read-and-process-parse-command-line-arguments
'programing' 카테고리의 다른 글
| WPF의 dataGridCells에 패딩 설정 (0) | 2023.04.09 |
|---|---|
| 특정 커밋을 변경하려면 어떻게 해야 합니까? (0) | 2023.04.09 |
| VBA + Excel + Try Catch (0) | 2023.04.09 |
| List에서 상속하지 않는 이유는 무엇입니까? (0) | 2023.04.09 |
| SQL Server: 여러 행을 하나의 행으로 결합 (0) | 2023.04.09 |