2016-08-08 2 views
2

저는 Python을 처음 사용합니다. 나는 유닉스 commmands ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")의 목록을 가지고 있으며 그들을 실행하고 전체 출력을 .txt 파일로 리디렉션하고 싶습니다. 나는 많은 것을 수색했으나 적절한 해결책을 얻지 못했거나 잘못 이해했다.os.system() 출력을 .txt 파일로 리디렉션하려면

이 for 루프를 사용하여 stdout에서 출력을 가져올 수 있지만 파일로 리디렉션 할 수 없습니다.

def commandsoutput(): 
    command = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev") 

    for i in command: 
     print (os.system(i)) 

commandsoutput() 
+2

는'stdout'을 리디렉션 할 수있는'subprocess' 모듈을 살펴 있습니다. –

답변

1

이 대답은 당신이 당신의 파일에 명령의 출력을 쓸 수있는 os.popen을 사용

import os 
def commandsoutput(): 
    commands = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev") 
    with open('output.txt','a') as outfile: 
     for command in commands: 
      outfile.write(os.popen(command).read()+"\n") 
commandsoutput() 
+0

감사합니다. 완벽하게 작동했습니다. – sharath

3

os.system 명령의 종료 코드가 아닌 출력을 반환합니다. 또한 사용되지 않습니다. 대신

사용 subprocess :

import subprocess 

def commandsoutput(): 
    command = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev") 

    with open('log.txt', 'a') as outfile: 
     for i in command: 
       subprocess.call(i, stdout=outfile) 

commandsoutput() 
+0

응답을 보내 주셔서 감사합니다.이 오류가 발생합니다. – sharath

+0

역 추적 (마지막으로 가장 최근 통화) : 파일 "test2.py", 10 행, commandsoutput에서() 파일 "test2.py", 8 호선, commandsoutput에서 subprocess.call (I, 표준 출력 = OUTFILE) 파일 "/usr/local/lib/python2.7/subprocess.py"522 행, 전화 반환 Popen (* popenargs, ** kwargs) .wait() 파일 "/ usr/local/lib/python2 _execute_child 인상 child_exception에서 0.7/subprocess.py "__init__ errread, errwrite에서, 라인 (709)) 파일"/usr/local/lib/python2.7/subprocess.py "라인 1326 OSError [ERRNO 2] 해당 파일 또는 디렉토리 없음 – sharath

관련 문제