>  기사  >  백엔드 개발  >  Python에서 쉘을 실행하는 두 가지 방법 요약

Python에서 쉘을 실행하는 두 가지 방법 요약

高洛峰
高洛峰원래의
2017-02-07 17:20:041155검색

1. Python에 내장된 명령 모듈을 사용하여 쉘 실행

commands는 Python의 os.popen()을 캡슐화하고 SHELL 명령 문자열을 매개변수로 사용하며 명령의 결과 데이터를 반환합니다. ;

이 명령은 현재 폐기되었으며 하위 프로세스로 대체되었습니다.

# coding=utf-8
'''
Created on 2013年11月22日
  
@author: crazyant.net
'''
import commands
import pprint
  
def cmd_exe(cmd_String):
  print "will exe cmd,cmd:"+cmd_String
  return commands.getstatusoutput(cmd_String)
  
if __name__=="__main__":
  pprint.pprint(cmd_exe("ls -la"))

2. Python의 최신 하위 프로세스 모듈을 사용하여 셸을 실행합니다

Python은 현재 다른 언어로 명령을 실행하기 위해 os.system, os.spawn*, os.popen*, popen2.*, Commands.*를 버렸습니다. 하위 프로세스를 사용하는 것이 좋습니다.

하위 프로세스를 사용하면 됩니다. 많은 하위 프로세스 생성 프로세스를 생성할 때 하위 프로세스와 해당 하위 프로세스의 입력, 출력, 오류 출력 파이프를 지정할 수 있으며, 실행 후 출력 결과와 실행 상태를 얻을 수 있습니다.

# coding=utf-8
'''
Created on 2013年11月22日
  
@author: crazyant.net
'''
import shlex
import datetime
import subprocess
import time
  
def execute_command(cmdstring, cwd=None, timeout=None, shell=False):
  """执行一个SHELL命令
      封装了subprocess的Popen方法, 支持超时判断,支持读取stdout和stderr
      参数:
    cwd: 运行命令时更改路径,如果被设定,子进程会直接先更改当前路径到cwd
    timeout: 超时时间,秒,支持小数,精度0.1秒
    shell: 是否通过shell运行
  Returns: return_code
  Raises: Exception: 执行超时
  """
  if shell:
    cmdstring_list = cmdstring
  else:
    cmdstring_list = shlex.split(cmdstring)
  if timeout:
    end_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
   
  #没有指定标准输出和错误输出的管道,因此会打印到屏幕上;
  sub = subprocess.Popen(cmdstring_list, cwd=cwd, stdin=subprocess.PIPE,shell=shell,bufsize=4096)
   
  #subprocess.poll()方法:检查子进程是否结束了,如果结束了,设定并返回码,放在subprocess.returncode变量中
  while sub.poll() is None:
    time.sleep(0.1)
    if timeout:
      if end_time <= datetime.datetime.now():
        raise Exception("Timeout:%s"%cmdstring)
       
  return str(sub.returncode)
  
if __name__=="__main__":
  print execute_command("ls")

Popen에서는 stdin, stdout을 변수로 지정하여 출력변수 값을 바로 받아볼 수도 있습니다.

요약

Python의 스레드 메커니즘을 사용하여 다양한 쉘 프로세스를 시작하는 등 Python에서 SHELL을 실행해야 하는 경우가 있습니다. 현재 Python에서 공식적으로 권장하는 방법 및 지원되는 기능은 subprocess입니다. 또한 가장 인기가 높으며 모든 사람이 사용하는 것이 좋습니다.

그렇습니다. 이 글의 내용이 모든 분들의 공부나 업무에 도움이 되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨주세요.

파이썬에서 쉘을 실행하는 두 가지 방법을 요약한 관련 기사를 더 보려면 PHP 중국어 웹사이트를 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.