문제

나는 이런 명령이있다.

wmctrl -lp | awk '/gedit/ { print $1 }'

그리고 파이썬 스크립트 내에서 출력을 원합니다.이 코드를 시도했습니다.

>>> import subprocess
>>> proc =  subprocess.Popen(["wmctrl -lp", "|","awk '/gedit/ {print $1}"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> proc.stdout.readline()
'0x0160001b -1 6504   beer-laptop x-nautilus-desktop\n'
>>> proc.stdout.readline()
'0x0352f117  0 6963   beer-laptop How to get output from external command combine with Pipe - Stack Overflow - Chromium\n'
>>> proc.stdout.readline()
'0x01400003 -1 6503   beer-laptop Bottom Expanded Edge Panel\n'
>>> 

내 코드가 틀린 것 같습니다 wmctrl -lp 실행 및 | awk '{print $1}' 내 기대 출력이 원하는 것으로 생략되었습니다 0x03800081

$ wmctrl -lp | awk '/gedit/ {print $1}'
0x03800081

도와주세요.

도움이 되었습니까?

해결책

와 함께 shell=True, 배열 대신 단일 명령 줄을 사용해야합니다. 그렇지 않으면 추가 인수는 쉘 인수로 해석됩니다. 로부터 subprocess 선적 서류 비치:

Unix에서 shell = true : args가 문자열 인 경우 쉘을 통해 실행하도록 명령 문자열을 지정합니다. Args가 시퀀스 인 경우 첫 번째 항목은 명령 문자열을 지정하고 추가 항목은 추가 쉘 인수로 취급됩니다.

그래서 당신의 전화는 다음과 같아야합니다.

subprocess.Popen("wmctrl -lp | sed /gedit/ '{print $1}'", shell=True, ...

나는 당신이 거기에 불균형 한 단일 견적을 가지고있을 것 같아요.

다른 팁

프로그램의 시퀀스를 전달하기 때문에 파이프가 논쟁 에게 wmcrtrl, 당신이 한 것처럼

wmctrl -lp "|"

따라서 실제 파이프 작업 손실됩니다.

단일 문자열로 만드는 것은 실제로 올바른 결과를 제공해야합니다.

>>> import subprocess as s
>>> proc = s.Popen("echo hello | grep e", shell=True, stdout=s.PIPE, stderr=s.PIPE)
>>> proc.stdout.readline()
'hello\n'
>>> proc.stdout.readline()
''

일부 연구 후에는 다음과 같은 코드가 있습니다. 기본적으로 stdout과 stderr를 실시간으로 인쇄합니다. 그것이 필요한 다른 사람을 도울 수 있기를 바랍니다.

stdout_result = 1
stderr_result = 1


def stdout_thread(pipe):
    global stdout_result
    while True:
        out = pipe.stdout.read(1)
        stdout_result = pipe.poll()
        if out == '' and stdout_result is not None:
            break

        if out != '':
            sys.stdout.write(out)
            sys.stdout.flush()


def stderr_thread(pipe):
    global stderr_result
    while True:
        err = pipe.stderr.read(1)
        stderr_result = pipe.poll()
        if err == '' and stderr_result is not None:
            break

        if err != '':
            sys.stdout.write(err)
            sys.stdout.flush()


def exec_command(command, cwd=None):
    if cwd is not None:
        print '[' + ' '.join(command) + '] in ' + cwd
    else:
        print '[' + ' '.join(command) + ']'

    p = subprocess.Popen(
        command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd
    )

    out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p,))
    err_thread = threading.Thread(name='stderr_thread', target=stderr_thread, args=(p,))

    err_thread.start()
    out_thread.start()

    out_thread.join()
    err_thread.join()

    return stdout_result + stderr_result

필요할 때는 문자열에서 출력 또는 오류를 쉽게 수집하고 반환하는 것이 쉽다고 생각합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top