이 코드가 있습니다 :
def hello():
return 'Hi :)'
커맨드 라인에서 어떻게 직접 실행합니까?
답변
-c
(command) 인수를 사용하여 ( 파일 이름이이라고 가정 foo.py
) :
$ python -c 'import foo; print foo.hello()'
또는 네임 스페이스 오염에 관심이없는 경우 :
$ python -c 'from foo import *; print hello()'
그리고 중간계 :
$ python -c 'from foo import hello; print hello()'
답변
hello()
함수 아래 어딘가에 놓으면 수행 할 때 실행됩니다.python your_file.py
깔끔한 솔루션의 경우 다음을 사용할 수 있습니다.
if __name__ == '__main__':
hello()
이렇게하면 파일을 가져올 때가 아니라 파일을 실행할 때만 함수가 실행됩니다.
답변
python -c 'from myfile import hello; hello()'
여기서 myfile
파이썬 스크립트의 기본 이름으로 바꿔야합니다. (예, myfile.py
진다myfile
).
그러나 hello()
파이썬 스크립트에서 “영구적 인”기본 진입 점 인 경우 일반적인 방법은 다음과 같습니다.
def hello():
print "Hi :)"
if __name__ == "__main__":
hello()
이것은 단순히 실행하여 스크립트를 실행 할 수 있습니다 python myfile.py
또는 python -m myfile
.
여기에 몇 가지 설명이 있습니다 : 명령 행에서 모듈이 시작될 때를 제외하고는__name__
현재 실행중인 모듈의 이름을 보유하는 특수한 Python 변수입니다 ."__main__"
답변
bash 명령 줄에서 호출 할 수있는 빠르고 작은 Python 스크립트를 작성했습니다. 호출하려는 모듈, 클래스 및 메소드의 이름과 전달하려는 매개 변수를 사용합니다. 나는 그것을 PyRun이라고 부르고 .py 확장자를 남겨두고 chmod + x PyRun으로 실행 가능하게 만들면 다음과 같이 빨리 호출 할 수 있습니다.
./PyRun PyTest.ClassName.Method1 Param1
이것을 PyRun이라는 파일에 저장하십시오
#!/usr/bin/env python
#make executable in bash chmod +x PyRun
import sys
import inspect
import importlib
import os
if __name__ == "__main__":
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
# get the second argument from the command line
methodname = sys.argv[1]
# split this into module, class and function name
modulename, classname, funcname = methodname.split(".")
# get pointers to the objects based on the string names
themodule = importlib.import_module(modulename)
theclass = getattr(themodule, classname)
thefunc = getattr(theclass, funcname)
# pass all the parameters from the third until the end of
# what the function needs & ignore the rest
args = inspect.getargspec(thefunc)
z = len(args[0]) + 2
params=sys.argv[2:z]
thefunc(*params)
작동 방식을 보여주는 샘플 모듈은 다음과 같습니다. 이것은 PyTest.py라는 파일에 저장됩니다.
class SomeClass:
@staticmethod
def First():
print "First"
@staticmethod
def Second(x):
print(x)
# for x1 in x:
# print x1
@staticmethod
def Third(x, y):
print x
print y
class OtherClass:
@staticmethod
def Uno():
print("Uno")
다음 예제를 실행하십시오.
./PyRun PyTest.SomeClass.First
./PyRun PyTest.SomeClass.Second Hello
./PyRun PyTest.SomeClass.Third Hello World
./PyRun PyTest.OtherClass.Uno
./PyRun PyTest.SomeClass.Second "Hello"
./PyRun PyTest.SomeClass.Second \(Hello, World\)
튜플을 튜플에 전달하기 위해 괄호를 이스케이프 처리하는 마지막 예를 참고하십시오.
메소드에 필요한 매개 변수가 너무 적 으면 오류가 발생합니다. 너무 많이 전달하면 추가 내용을 무시합니다. 모듈은 현재 작업 폴더에 있어야하며 PyRun은 경로의 어느 위치 에나 놓을 수 있습니다.
답변
이 스 니펫을 스크립트 하단에 추가하십시오.
def myfunction():
...
if __name__ == '__main__':
globals()[sys.argv[1]]()
이제 다음을 실행하여 함수를 호출 할 수 있습니다.
python myscript.py myfunction
이것은 명령 줄 인수 (함수 이름의 문자열)를 전달하기 때문에 작동합니다 locals
현재 로컬 심볼 테이블이있는 사전에 합니다. 마지막에있는 패리티 스는 함수를 호출 할 것입니다.
업데이트 : 함수가 명령 줄에서 매개 변수를 수락하도록하려면 다음 sys.argv[2]
과 같이 전달 하십시오.
def myfunction(mystring):
print mystring
if __name__ == '__main__':
globals()[sys.argv[1]](sys.argv[2])
이렇게하면 running python myscript.py myfunction "hello"
이 출력 hello
됩니다.
답변
이것을 좀 더 쉽게 만들고 모듈을 사용합시다 …
시험: pip install compago
그런 다음 다음을 작성하십시오.
import compago
app = compago.Application()
@app.command
def hello():
print "hi there!"
@app.command
def goodbye():
print "see ya later."
if __name__ == "__main__":
app.run()
그런 다음 다음과 같이 사용하십시오.
$ python test.py hello
hi there!
$ python test.py goodbye
see ya later.
참고 : 현재 Python 3 에는 버그 가 있지만 Python 2에서는 훌륭하게 작동합니다.
편집 : 더 나은 옵션은 제 의견으로는 함수 인수를 쉽게 전달할 수있는 Google 의 모듈 화재 입니다. 와 함께 설치됩니다 pip install fire
. 그들의 GitHub에서 :
다음은 간단한 예입니다.
import fire
class Calculator(object):
"""A simple calculator class."""
def double(self, number):
return 2 * number
if __name__ == '__main__':
fire.Fire(Calculator)
그런 다음 명령 행에서 다음을 실행할 수 있습니다.
python calculator.py double 10 # 20
python calculator.py double --number=15 # 30
답변
흥미롭게도, 목표가 명령 행 콘솔에 인쇄하거나 다른 작은 파이썬 작업을 수행하는 것이라면 입력을 다음과 같이 파이썬 인터프리터로 파이프 할 수 있습니다.
echo print("hi:)") | python
파이프 파일뿐만 아니라
python < foo.py
* 두 번째가 작동하기 위해 확장명이 .py 일 필요는 없습니다. ** 또한 bash의 경우 문자를 이스케이프해야 할 수도 있습니다.
echo print\(\"hi:\)\"\) | python