2013-03-24 2 views
2

os.system을 사용하여 시스템에 명령을 제출합니다.os.system 명령 제출

즉,

import os 
os.system(my_cmd) 

하지만 내가 출력을 얻을 수, 즉, 우리가 내가 bash는 오전 내 cmd를 입력 할 가정 해 봅시다 궁금 해서요,이 형태의 출력을 얻을 것 : 나는, 파이썬에서 os.system을 (cmd를) 사용하여, 또한 텍스트 출력을 구하고 작업 ID를 얻기 위해 구문 분석 할 수있는 방법

Job <57960787> is submitted to queue <queueq>. 

, 57960787.

감사합니다!

+1

http://docs.python.org/2/library/subprocess.html 넌 '관()'프로세스 간 통신 –

+0

'나가서 설명하자면 NameError 이름 '서브 'is not defined' AND'AttributeError :'str '객체에'PIPE '속성이 없습니다. 영업일을 확인하십시오. –

답변

6

은 아래 예제 subprocess 모듈 문서 here를 사용하는 것이 좋습니다 :

import subprocess,re 
p = subprocess.Popen('commands',stdout=subprocess.PIPE,stderr=subprocess.PIPE) 
results, errors = p.communicate() 
print results 
re.search('<(\d+)>', results).group(1) #Cheers, Jon Clements 

아니면 심지어 os.popen 문서 here를 사용할 수 있습니다

p_os = os.popen("commands","r") 
line = p_os.readline() 
print line 
re.search('<(\d+)>', line).group(1) #Cheers, Jon Clements 

또는 존 클레멘트 친절 제안, 당신이 할 수있는

subprocess.check_output, 사용 설명서 here

>>> subprocess.check_output(["echo", "Hello World!"]) 
'Hello World!\n' 
+0

1 예를 필요 –

+0

@Allendar가 수정되었습니다. – enginefree

+0

우수. 건배 :) +1 –

1

간단한 예 :

>>> import os, sys 
>>> cmd = "uname" 
>>> b = os.popen(cmd, 'r', 1) 
>>> b.read() 
'Linux\n' 

나는 리눅스 uname 명령을 실행하고 있습니다.

os.popen()은 명령을 실행하고 명령 출력을 읽을 수있는 파일 형식 개체를 반환합니다.

0

os.system 출력을 반환하지 않습니다. 따라서 대신 commands 모듈을 사용할 수 있습니다.

예 :

import commands 
my_cmd = 'ls -l' 
status, output = commands.getstatusoutput(my_cmd) 
print output