Programming

스크립트에서 sys.argv [1] 의미

procodes 2020. 6. 30. 21:25
반응형

스크립트에서 sys.argv [1] 의미


나는 현재 파이썬을 가르치고 있으며 (아래 예제와 관련하여) 단순화 된 용어로 sys.argv[1]표현이 무엇인지 궁금합니다 . 단순히 입력을 요구합니까?

#!/usr/bin/python3.1

# import modules used here -- sys is a very standard one
import sys

# Gather our code in a main() function
def main():
  print ('Hello there', sys.argv[1])
  # Command line args are in sys.argv[1], sys.argv[2] ..
  # sys.argv[0] is the script name itself and can be ignored

# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
  main()

이전 답변이 사용자의 지식에 대해 많은 가정을했음을 참고하고 싶습니다. 이 답변은 더 많은 튜토리얼 수준에서 질문에 답변을 시도합니다.

Python을 호출 할 때마다 sys.argv명령 줄에서 인수를 공백으로 구분하여 나타내는 문자열 목록이 자동으로 표시됩니다. 이름은 argv 및 argc가 명령 행 인수를 나타내는 C 프로그래밍 규칙 에서 나옵니다 .

파이썬에 익숙해지면 목록과 문자열에 대해 더 배우고 싶지만 그 동안 알아야 할 몇 가지 사항이 있습니다.

인수가 표현 된대로 인쇄하는 스크립트를 작성하면됩니다. 또한 len목록 함수를 사용하여 인수 수를 인쇄합니다 .

from __future__ import print_function
import sys
print(sys.argv, len(sys.argv))

이 스크립트에는 Python 2.6 이상이 필요합니다. 이 스크립트 print_args.py를 호출하면 다른 인수로 스크립트 를 호출하여 어떻게되는지 확인할 수 있습니다.

> python print_args.py
['print_args.py'] 1

> python print_args.py foo and bar
['print_args.py', 'foo', 'and', 'bar'] 4

> python print_args.py "foo and bar"
['print_args.py', 'foo and bar'] 2

> python print_args.py "foo and bar" and baz
['print_args.py', 'foo and bar', 'and', 'baz'] 4

보시다시피 명령 줄 인수에는 스크립트 이름이 포함되지만 인터프리터 이름은 포함되지 않습니다. 이런 의미에서 파이썬은 스크립트 실행 파일 취급합니다 . 실행 파일 이름 (이 경우 Python)을 알아야하는 경우을 사용할 수 있습니다 sys.executable.

예제에서 사용자가 따옴표로 묶은 인수로 스크립트를 호출 한 경우 공백이 포함 된 인수를 수신 할 수 있으므로 사용자가 제공 한 인수 목록이 표시됩니다.

이제 파이썬 코드에서이 문자열 목록을 프로그램의 입력으로 사용할 수 있습니다. 목록은 0부터 시작하는 정수로 색인화되므로 list [0] 구문을 사용하여 개별 항목을 가져올 수 있습니다. 예를 들어 스크립트 이름을 얻으려면

script_name = sys.argv[0] # this will always work.

흥미롭지 만 스크립트 이름을 거의 알 필요가 없습니다. 파일 이름에 대한 스크립트 다음에 첫 번째 인수를 얻으려면 다음을 수행하십시오.

filename = sys.argv[1]

이것은 매우 일반적인 사용법이지만 인수가 제공되지 않으면 IndexError와 함께 실패합니다.

또한 Python을 사용하면 목록 조각을 참조 할 수 있으므로 사용자 제공 인수의 다른 목록 (스크립트 이름이없는) 을 가져 오려면 다음을 수행 할 수 있습니다.

user_args = sys.argv[1:] # get everything after the script name

또한 Python을 사용하면 변수 이름에 일련의 항목 (목록 포함)을 지정할 수 있습니다. 따라서 사용자가 항상 두 개의 인수를 제공 할 것으로 예상되면 해당 인수 (문자열)를 두 개의 변수에 지정할 수 있습니다.

user_args = sys.argv[1:]
fun, games = user_args # len(user_args) had better be 2

따라서 특정 질문에 대답하기 위해 문제 의 스크립트에 제공된 sys.argv[1]첫 번째 명령 줄 인수 ()를 나타냅니다 string. 입력을 요구하지는 않지만 스크립트 이름 다음에 명령 행에 인수가 제공되지 않으면 IndexError와 함께 실패합니다.


sys.argv [1] 에는 스크립트에 전달 된 첫 번째 명령 줄 인수 가 포함되어 있습니다.

예를 들어, 스크립트 이름이 지정되어 hello.py있고 발행 한 경우 :

$ python3.1 hello.py foo

또는:

$ chmod +x hello.py  # make script executable
$ ./hello.py foo

스크립트가 인쇄됩니다 :

안녕하세요 foo

sys.argv 목록입니다.

This list is created by your command line, it's a list of your command line arguments.

For example:

in your command line you input something like this,

python3.2 file.py something

sys.argv will become a list ['file.py', 'something']

In this case sys.argv[1] = 'something'


Just adding to Frederic's answer, for example if you call your script as follows:

./myscript.py foo bar

sys.argv[0] would be "./myscript.py" sys.argv[1] would be "foo" and sys.argv[2] would be "bar" ... and so forth.

In your example code, if you call the script as follows ./myscript.py foo , the script's output will be "Hello there foo".


Adding a few more points to Jason's Answer :

For taking all user provided arguments : user_args = sys.argv[1:]

Consider the sys.argv as a list of strings as (mentioned by Jason). So all the list manipulations will apply here. This is called "List Slicing". For more info visit here.

The syntax is like this : list[start:end:step]. If you omit start, it will default to 0, and if you omit end, it will default to length of list.

Suppose you only want to take all the arguments after 3rd argument, then :

user_args = sys.argv[3:]

Suppose you only want the first two arguments, then :

user_args = sys.argv[0:2]  or  user_args = sys.argv[:2]

Suppose you want arguments 2 to 4 :

user_args = sys.argv[2:4]

Suppose you want the last argument (last argument is always -1, so what is happening here is we start the count from back. So start is last, no end, no step) :

user_args = sys.argv[-1]

Suppose you want the second last argument :

user_args = sys.argv[-2]

Suppose you want the last two arguments :

user_args = sys.argv[-2:]

Suppose you want the last two arguments. Here, start is -2, that is second last item and then to the end (denoted by ":") :

user_args = sys.argv[-2:]

Suppose you want the everything except last two arguments. Here, start is 0 (by default), and end is second last item :

user_args = sys.argv[:-2]

Suppose you want the arguments in reverse order :

user_args = sys.argv[::-1]

Hope this helps.


sys.argv is a list containing the script path and command line arguments; i.e. sys.argv[0] is the path of the script you're running and all following members are arguments.


To pass arguments to your python script while running a script via command line

python create_thumbnail.py test1.jpg test2.jpg

here, script name - create_thumbnail.py, argument 1 - test1.jpg, argument 2 - test2.jpg

With in the create_thumbnail.py script i use

sys.argv[1:]

which give me the list of arguments i passed in command line as ['test1.jpg', 'test2.jpg']


sys.argv is a attribute of the sys module. It says the arguments passed into the file in the command line. sys.argv[0] catches the directory where the file is located. sys.argv[1] returns the first argument passed in the command line. Think like we have a example.py file.

example.py

import sys # Importing the main sys module to catch the arguments
print(sys.argv[1]) # Printing the first argument

Now here in the command prompt when we do this:

python example.py

It will throw a index error at line 2. Cause there is no argument passed yet. You can see the length of the arguments passed by user using if len(sys.argv) >= 1: # Code. If we run the example.py with passing a argument

python example.py args

It prints:

args

Because it was the first arguement! Let's say we have made it a executable file using PyInstaller. We would do this:

example argumentpassed

It prints:

argumentpassed

It's really helpful when you are making a command in the terminal. First check the length of the arguments. If no arguments passed, do the help text.


sys .argv will display the command line args passed when running a script or you can say sys.argv will store the command line arguments passed in python while running from terminal.

Just try this:

import sys
print sys.argv

argv stores all the arguments passed in a python list. The above will print all arguments passed will running the script.

Now try this running your filename.py like this:

python filename.py example example1

this will print 3 arguments in a list.

sys.argv[0] #is the first argument passed, which is basically the filename. 

Similarly, argv1 is the first argument passed, in this case 'example'

A similar question has been asked already here btw. Hope this helps!

참고URL : https://stackoverflow.com/questions/4117530/sys-argv1-meaning-in-script

반응형