This article focuses on two methods of executing the shell in Python, two ways to execute shell programs in Python, one using Python's commands package, and two using the subprocess package. Both packages are Python's existing built-in modules. Need friends can reference, below to see together.
First, execute the shell using Python's built-in commands module
Commands encapsulates Python's Os.popen (), uses the shell command string as its parameter, returns the result data of the command, and the state of the command execution;
The order is now obsolete and replaced by subprocess;
?
123456789101112131415 |
# 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"
))
|
Second, use Python's latest subprocess module to execute the shell
Python has now abandoned os.system,os.spawn*,os.popen*,popen2.*,commands.* to execute commands in other languages, and Subprocesss is the recommended method;
Subprocess allows you to create many sub-processes that can be created to specify the input, output, and error output channels of the child and child processes, and to obtain the output and execution status after execution.
?
123456789101112131415161718192021222324252627282930313233343536373839404142 |
# 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"
)
|
You can also specify stdin and stdout as a variable in popen, so that you can receive the output variable value directly.
Summarize
Executing the shell in Python is sometimes also necessary, such as using Python's threading mechanism to start different shell processes, currently subprocess is the official Python recommendation, and it supports the most features, which are recommended for everyone to use.
Well, the above is the whole content of this article, I hope that the content of this article on everyone's study or work can bring certain help, if there is doubt you can message exchange.
Articles you may be interested in:
- C++/php/python language methods for executing shell commands (recommended)
- Python captures output instances of shell scripts
- Linux Server NIC traffic viewing method shell and Python each
- Python's implementation code to query Google keyword rankings with shell
- Bpython powerful Python shell
- Get hostname and FQDN based on Python shell
- An example of how Python calls the system shell under Linux system
- Python Shell gets host name code example based on IP
Original link: http://www.crazyant.net/1319.html
A summary of two methods of executing the shell in Python