파이프와 함께 서브 프로세스 명령을 사용하는 방법
subprocess.check_output()
와 함께 사용하고 싶습니다 ps -A | grep 'process_name'
. 다양한 솔루션을 시도했지만 지금까지 아무것도 효과가 없었습니다. 누군가 나를 어떻게 도울 수 있습니까?
subprocess
모듈 과 함께 파이프를 사용하려면 을 통과해야 shell=True
합니다.
그러나 이것은 여러 가지 이유로 실제로 권장되지는 않지만 보안은 최소한입니다. 대신 ps
및 grep
프로세스를 별도로 작성하고 다음 과 같이 출력을 서로 연결하십시오.
ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)
output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
ps.wait()
그러나 특별한 경우에 간단한 해결책은 출력 subprocess.check_output(('ps', '-A'))
후 호출 str.find
하는 것입니다.
또는 서브 프로세스 오브젝트에서 항상 통신 메소드를 사용할 수 있습니다.
cmd = "ps -A|grep 'process_name'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print output
communi 메소드는 표준 출력 및 표준 오류의 튜플을 리턴합니다.
하위 프로세스를 사용하여 파이프 라인 설정에 대한 문서를 참조하십시오. http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline
다음 코드 예제를 테스트하지는 않았지만 대략 원하는 것이어야합니다.
query = "process_name"
ps_process = Popen(["ps", "-A"], stdout=PIPE)
grep_process = Popen(["grep", query], stdin=ps_process.stdout, stdout=PIPE)
ps_process.stdout.close() # Allow ps_process to receive a SIGPIPE if grep_process exits.
output = grep_process.communicate()[0]
JKALAVIS 솔루션은 좋지만 SHELL = TRUE 대신 shlex를 사용하도록 개선했습니다. 아래는 쿼리 시간을 없애는 것
#!/bin/python
import subprocess
import shlex
cmd = "dig @8.8.4.4 +notcp www.google.com|grep 'Query'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print output
건배,
sh.py 에서 파이프 기능을 사용해 볼 수 있습니다 .
import sh
print sh.grep(sh.ps("-ax"), "process_name")
또한 'pgrep'
대신에 명령 을 사용하십시오'ps -A | grep 'process_name'
참고 URL : https://stackoverflow.com/questions/13332268/how-to-use-subprocess-command-with-pipes
'Programing' 카테고리의 다른 글
.join () 메소드는 정확히 무엇을합니까? (0) | 2020.05.06 |
---|---|
스칼라에서 목록의 끝에 요소 추가 (0) | 2020.05.06 |
jQuery를 사용하여 테이블 셀 값을 얻는 방법은 무엇입니까? (0) | 2020.05.06 |
도커 컨테이너에서 호스트 포트에 액세스하는 방법 (0) | 2020.05.06 |
동적 프로그래밍을 사용하여 가장 긴 하위 시퀀스를 결정하는 방법은 무엇입니까? (0) | 2020.05.06 |