복붙노트

[PYTHON] 셸 명령에서 파이썬 스크립트로 파이프 출력

PYTHON

셸 명령에서 파이썬 스크립트로 파이프 출력

mysql 명령을 실행하고 그 출력을 파이썬 스크립트의 변수로 설정하려고합니다.

다음은 실행하려는 쉘 명령입니다.

$ mysql my_database --html -e "select * from limbs" | ./script.py

다음은 python 스크립트입니다.

#!/usr/bin/env python

import sys

def hello(variable):
    print variable

어떻게하면 python 스크립트의 변수를 받아들이고 출력을 출력 할 수 있습니까?

해결법

  1. ==============================

    1.예를 들어 표준 입력에서 읽으면 파이썬 스크립트에서 데이터를 가져와야합니다.

    예를 들어 표준 입력에서 읽으면 파이썬 스크립트에서 데이터를 가져와야합니다.

    #!/usr/bin/env python
    
    import sys
    
    def hello(variable):
        print variable
    
    data = sys.stdin.read()
    hello(data)
    

    여기서 원하는 것은 mysql 데이터베이스의 데이터를 가져 와서 파이썬으로 조작하는 것이다. 파이핑을 건너 뛰고 Python MySql 모듈을 사용하여 SQL 쿼리를 수행한다.

  2. ==============================

    2.스크립트가 많은 유닉스 명령 행 도구처럼 동작하고 파이프 또는 파일 이름을 첫 번째 인수로 받아들이게하려면 다음을 사용할 수 있습니다.

    스크립트가 많은 유닉스 명령 행 도구처럼 동작하고 파이프 또는 파일 이름을 첫 번째 인수로 받아들이게하려면 다음을 사용할 수 있습니다.

    #!/usr/bin/env python
    import sys
    
    # use stdin if it's full                                                        
    if not sys.stdin.isatty():
        input_stream = sys.stdin
    
    # otherwise, read the given filename                                            
    else:
        try:
            input_filename = sys.argv[1]
        except IndexError:
            message = 'need filename as first argument if stdin is not full'
            raise IndexError(message)
        else:
            input_stream = open(input_filename, 'rU')
    
    for line in input_stream:
        print line # do something useful with each line
    
  3. ==============================

    3.한 명령의 출력을 파이썬 스크립트로 파이프하면 sys.stdin으로 이동합니다. 파일처럼 sys.stdin에서 읽을 수 있습니다. 예:

    한 명령의 출력을 파이썬 스크립트로 파이프하면 sys.stdin으로 이동합니다. 파일처럼 sys.stdin에서 읽을 수 있습니다. 예:

    import sys
    
    print sys.stdin.read()
    

    이 프로그램은 말 그대로 입력을 출력합니다.

  4. ==============================

    4.Python 스크립트에 대한 파이핑 데이터를 검색 할 때이 대답이 Google의 상단에 표시되기 때문에 J Beazley의 Python Cookbook에서 사용한 것보다 덜 껄끄 러운 aproach를 찾은 다른 방법을 추가하고 싶습니다. sys. IMO는 새로운 사용자에게조차도 파이썬 적이거나 자명합니다.

    Python 스크립트에 대한 파이핑 데이터를 검색 할 때이 대답이 Google의 상단에 표시되기 때문에 J Beazley의 Python Cookbook에서 사용한 것보다 덜 껄끄 러운 aproach를 찾은 다른 방법을 추가하고 싶습니다. sys. IMO는 새로운 사용자에게조차도 파이썬 적이거나 자명합니다.

    import fileinput
    with fileinput.input() as f_input:
        for line in f_input:
            print(line, end='')
    

    이 방법은 다음과 같이 구조화 된 명령에서도 작동합니다.

    $ ls | ./filein.py          # Prints a directory listing to stdout.
    $ ./filein.py /etc/passwd   # Reads /etc/passwd to stdout.
    $ ./filein.py < /etc/passwd # Reads /etc/passwd to stdout.
    

    좀 더 복잡한 솔루션이 필요하다면, martinth에 의해 다음과 같이 argparse와 fileinput을 컴파일 할 수 있습니다 :

    import argpase
    import fileinput
    
    if __name__ == '__main__':
        parser = ArgumentParser()
        parser.add_argument('--dummy', help='dummy argument')
        parser.add_argument('files', metavar='FILE', nargs='*', help='files to read, if empty, stdin is used')
        args = parser.parse_args()
    
        # If you would call fileinput.input() without files it would try to process all arguments.
        # We pass '-' as only file when argparse got no files which will cause fileinput to read from stdin
        for line in fileinput.input(files=args.files if len(args.files) > 0 else ('-', )):
            print(line)
    

    ```

  5. ==============================

    5.필자는 필자가 작성하지 않은 파이썬 스크립트에 bash 명령을 파이프하는 것을 우연히 발견했다. (그리고 sys.stdin을 받아들이 기 위해 수정하고 싶지 않았다.) 여기에서 언급 한 프로세스 대체가 제대로 작동하는 것을 발견했습니다 (https://superuser.com/questions/461946/can-i-use-pipe-output-as-a-shell-script-argument).

    필자는 필자가 작성하지 않은 파이썬 스크립트에 bash 명령을 파이프하는 것을 우연히 발견했다. (그리고 sys.stdin을 받아들이 기 위해 수정하고 싶지 않았다.) 여기에서 언급 한 프로세스 대체가 제대로 작동하는 것을 발견했습니다 (https://superuser.com/questions/461946/can-i-use-pipe-output-as-a-shell-script-argument).

    전의. some_script.py -arg1 <(배쉬 명령어)

  6. from https://stackoverflow.com/questions/11109859/pipe-output-from-shell-command-to-a-python-script by cc-by-sa and MIT license