#! (shebang) Python 스크립트에서 어떤 형식을 취해야합니까?
파이썬 스크립트에 shebang을 넣어야합니까? 어떤 형태로?
#!/usr/bin/env python
또는
#!/usr/local/bin/python
이것들은 똑같이 휴대 가능합니까? 어떤 형식이 가장 많이 사용됩니까?
참고 : 토네이도 프로젝트는 오두막을 사용합니다. 반면에 Django 프로젝트는 그렇지 않습니다.
스크립트의 shebang 줄 python
은 터미널에 미리 입력하지 않고 또는 파일 관리자에서 두 번 클릭 할 때 (적절하게 구성된 경우) 독립 실행 형 실행 파일처럼 스크립트가 실행될 수 있는지 여부를 결정합니다 . 필요하지는 않지만 일반적으로 거기에두기 때문에 누군가 편집기에서 열린 파일을 보면 즉시보고있는 것을 알 수 있습니다. 그러나, 당신이 사용하는 오두막 라인 입니다 중요합니다.
Python 3 스크립트의 올바른 사용법은 다음과 같습니다.
#!/usr/bin/env python3
기본값은 3.latest 버전입니다. 파이썬 2.7.latest 사용하는 python2
대신에 python3
.
다음 은 사용해서는 안됩니다 (Python 2.x 및 3.x와 호환되는 코드를 작성하는 드문 경우 제외).
#!/usr/bin/env python
에 주어진 이러한 권장 사항에 대한 이유, PEP 394 , 즉 python
하려면 다음 중 하나를 참조 할 수 있습니다 python2
또는 python3
다른 시스템에. 현재 python2
대부분의 배포판을 참조하지만 언젠가는 변경 될 수 있습니다.
또한 다음을 사용하지 마십시오.
#!/usr/local/bin/python
"python은 / usr / bin / python 또는 / bin / python에 설치 될 수 있습니다. 위의 #!는 실패합니다."
- "#! / usr / bin / env python"대 "#! / usr / local / bin / python"
정말 맛의 문제입니다. shebang을 추가하면 사람들이 원하는 경우 스크립트를 직접 호출 할 수 있습니다 (실행 파일로 표시되었다고 가정). 생략하면 python
수동으로 호출해야 함을 의미 합니다.
프로그램 실행의 최종 결과는 어느 쪽이든 영향을받지 않습니다. 수단의 선택 일뿐입니다.
파이썬 스크립트에 shebang을 넣어야합니까?
다음을 나타 내기 위해 Python 스크립트에 shebang을 넣으십시오.
- 이 모듈은 스크립트로 실행할 수 있습니다.
- python2, python3에서만 실행할 수 있는지 아니면 Python 2/3와 호환되는지 여부
- POSIX에서는
python
명시 적으로 실행 파일 을 호출하지 않고 스크립트를 직접 실행하려는 경우 필요합니다.
이것들은 똑같이 휴대 가능합니까? 어떤 형식이 가장 많이 사용됩니까?
shebang을 수동으로 작성하는 경우 사용 #!/usr/bin/env python
하지 않을 특별한 이유가없는 한 항상 사용하십시오. 이 형식은 Windows (Python 런처)에서도 이해됩니다.
참고 : 설치된 스크립트는 특정 Python 실행 파일 (예 : /usr/bin/python
또는 /home/me/.virtualenvs/project/bin/python
. 쉘에서 virtualenv를 활성화하면 일부 도구가 중단되는 것은 좋지 않습니다. 다행히 대부분의 경우 setuptools
또는 배포 패키지 도구에 의해 올바른 shebang이 자동으로 생성됩니다 (Windows에서는 setuptools
래퍼 .exe
스크립트를 자동으로 생성 할 수 있음 ).
즉, 스크립트가 소스 체크 아웃에있는 경우 #!/usr/bin/env python
. 설치되어있는 경우 shebang은 다음과 같은 특정 Python 실행 파일의 경로입니다 #!/usr/local/bin/python
(참고 : 후자 범주의 경로를 수동으로 작성해서는 안 됨).
사용할지 여부를 선택합니다 python
, python2
또는 python3
오두막에서 참조 PEP 394 - 유닉스 계열 시스템에 "파이썬"명령을 :
...
python
Python 2 및 3과 소스가 호환되는 스크립트에 대해서만 shebang 줄에서 사용해야합니다.Python 기본 버전의 최종 변경에 대비하여 Python 2 전용 스크립트는 Python 3과 소스 호환되도록 업데이트하거나
python2
shebang 라인에서 사용하도록 업데이트해야합니다 .
둘 이상의 Python 버전이 있고 스크립트를 특정 버전에서 실행해야하는 경우 she-bang은 스크립트가 직접 실행될 때 올바른 버전이 사용되도록 할 수 있습니다. 예를 들면 다음과 같습니다.
#!/usr/bin/python2.7
스크립트는 여전히 완전한 Python 명령 줄을 통해 또는 가져 오기를 통해 실행될 수 있으며,이 경우 she-bang이 무시됩니다. 그러나 스크립트가 직접 실행되는 경우 이것이 she-bang을 사용하는 적절한 이유입니다.
#!/usr/bin/env python
일반적으로 더 나은 방법이지만 특별한 경우에 도움이됩니다.
일반적으로 Python 가상 환경을 설정하는 것이 더 낫습니다.이 경우 제네릭 #!/usr/bin/env python
은 virtualenv에 대한 올바른 Python 인스턴스를 식별합니다.
스크립트가 실행 가능하도록 의도 된 경우 shebang을 추가해야합니다. 대상 플랫폼에서 작동하도록 shebang을 올바른 것으로 수정하는 설치 소프트웨어로 스크립트를 설치해야합니다. 이에 대한 예로 distutils 및 Distribute가 있습니다.
shebang의 목적은 쉘에서 스크립트를 실행하려고 할 때 스크립트가 인터프리터 유형을 인식하는 것입니다. 항상 그런 것은 아니지만 대부분 외부에서 인터프리터를 제공하여 스크립트를 실행합니다. 사용 예 :python-x.x script.py
shebang 선언자가없는 경우에도 작동합니다.
첫 번째 것이 더 "이동 가능"한 이유는 시스템 실행 파일이있는 모든 대상을 설명하는 선언이 /usr/bin/env
포함되어 있기 때문 PATH
입니다.
NOTE: Tornado doesn't strictly use shebangs, and Django strictly doesn't. It varies with how you are executing your application's main function.
ALSO: It doesn't vary with Python.
Sometimes, if the answer is not very clear (I mean you cannot decide if yes or no), then it does not matter too much, and you can ignore the problem until the answer is clear.
The #!
only purpose is for launching the script. Django loads the sources on its own and uses them. It never needs to decide what interpreter should be used. This way, the #!
actually makes no sense here.
Generally, if it is a module and cannot be used as a script, there is no need for using the #!
. On the other hand, a module source often contains if __name__ == '__main__': ...
with at least some trivial testing of the functionality. Then the #!
makes sense again.
One good reason for using #!
is when you use both Python 2 and Python 3 scripts -- they must be interpreted by different versions of Python. This way, you have to remember what python
must be used when launching the script manually (without the #!
inside). If you have a mixture of such scripts, it is a good idea to use the #!
inside, make them executable, and launch them as executables (chmod ...).
When using MS-Windows, the #!
had no sense -- until recently. Python 3.3 introduces a Windows Python Launcher (py.exe and pyw.exe) that reads the #!
line, detects the installed versions of Python, and uses the correct or explicitly wanted version of Python. As the extension can be associated with a program, you can get similar behaviour in Windows as with execute flag in Unix-based systems.
When I installed Python 3.6.1 on Windows 7 recently, it also installed the Python Launcher for Windows, which is supposed to handle the shebang line. However, I found that the Python Launcher did not do this: the shebang line was ignored and Python 2.7.13 was always used (unless I executed the script using py -3).
To fix this, I had to edit the Windows registry key HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Python.File\shell\open\command
. This still had the value
"C:\Python27\python.exe" "%1" %*
from my earlier Python 2.7 installation. I modified this registry key value to
"C:\Windows\py.exe" "%1" %*
and the Python Launcher shebang line processing worked as described above.
Answer: Only if you plan to make it a command-line executable script.
Here is the procedure:
Start off by verifying the proper shebang string to use:
which python
Take the output from that and add it (with the shebang #!) in the first line.
On my system it responds like so:
$which python
/usr/bin/python
So your shebang will look like:
#!/usr/bin/python
After saving, it will still run as before since python will see that first line as a comment.
python filename.py
To make it a command, copy it to drop the .py extension.
cp filename.py filename
Tell the file system that this will be executable:
chmod +x filename
To test it, use:
./filename
Best practice is to move it somewhere in your $PATH so all you need to type is the filename itself.
sudo cp filename /usr/sbin
That way it will work everywhere (without the ./ before the filename)
다른 모듈이 설치되어 있고 특정 Python 설치를 사용해야하는 경우 처음에는 shebang이 제한된 것으로 보입니다. 그러나 다음과 같은 트릭을 수행하여 shebang을 먼저 쉘 스크립트로 호출 한 다음 python을 선택할 수 있습니다. 이것은 매우 유연한 imo입니다.
#!/bin/sh
#
# Choose the python we need. Explanation:
# a) '''\' translates to \ in shell, and starts a python multi-line string
# b) "" strings are treated as string concat by python, shell ignores them
# c) "true" command ignores its arguments
# c) exit before the ending ''' so the shell reads no further
# d) reset set docstrings to ignore the multiline comment code
#
"true" '''\'
PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3
if [ -x $PREFERRED_PYTHON ]; then
echo Using preferred python $ALTERNATIVE_PYTHON
exec $PREFERRED_PYTHON "$0" "$@"
elif [ -x $ALTERNATIVE_PYTHON ]; then
echo Using alternative python $ALTERNATIVE_PYTHON
exec $ALTERNATIVE_PYTHON "$0" "$@"
else
echo Using fallback python $FALLBACK_PYTHON
exec python3 "$0" "$@"
fi
exit 127
'''
__doc__ = """What this file does"""
print(__doc__)
import platform
print(platform.python_version())
또는 더 나은 방법은 여러 Python 스크립트에서 코드 재사용을 용이하게하는 것입니다.
#!/bin/bash
"true" '''\'; source $(cd $(dirname ${BASH_SOURCE[@]}) &>/dev/null && pwd)/select.sh; exec $CHOSEN_PYTHON "$0" "$@"; exit 127; '''
select.sh에는 다음이 있습니다.
PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3
if [ -x $PREFERRED_PYTHON ]; then
CHOSEN_PYTHON=$PREFERRED_PYTHON
elif [ -x $ALTERNATIVE_PYTHON ]; then
CHOSEN_PYTHON=$ALTERNATIVE_PYTHON
else
CHOSEN_PYTHON=$FALLBACK_PYTHON
fi
먼저 사용
which python
이것은 내 파이썬 인터프리터 (바이너리)가있는 위치로 출력을 제공합니다.
이 출력은 다음과 같을 수 있습니다.
/usr/bin/python
또는
/bin/python
이제 적절하게 shebang 라인을 선택하고 사용하십시오.
일반화하려면 다음을 사용할 수 있습니다.
#!/usr/bin/env
또는
#!/bin/env
'Programing' 카테고리의 다른 글
탭-공간 변환 계수를 사용자 정의하는 방법은 무엇입니까? (0) | 2020.09.30 |
---|---|
펜촉이 장착되었지만 '보기'콘센트가 설정되지 않았습니다. (0) | 2020.09.30 |
Razor보기 페이지에서 네임 스페이스를 가져 오려면 어떻게하나요? (0) | 2020.09.30 |
파이썬에서 do-while 루프를 에뮬레이트합니까? (0) | 2020.09.30 |
Git에서 유효하지 않은 원격 분기 참조를 어떻게 제거합니까? (0) | 2020.09.30 |