Python|python中执行linux命令(调用linux命令)

#传参调用exe程序(解决相对路径,觉得路径问题),等待exe进程结束,此程序才结束。# -*- coding: utf-8-*-import os, os.path, sys import win32process, win32eventexe_path = sys.argv[1] exe_file = sys.argv[2]#os.chdir(exe_path)try : handle = win32process.CreateProcess(os.path.join(exe_path, exe_file), '', None, None, 0, win32process.CREATE_NO_WINDOW, None , exe_path, win32process.STARTUPINFO()) running = True except Exception, e: print "Create Error!" handle = None running = Falsewhile running : rc = win32event.WaitForSingleObject(handle[0], 1000) if rc == win32event.WAIT_OBJECT_0: running = False #end while print "GoodBye"

#需要用的模块:pywin32-214.win32-py2.5.exe
把改程序做成exe程序,就可以任何地方调用了(windows系统下)。


===========================================================================
两者均需 import os
(1) os.system
# 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息
system(command) -> exit_status
Execute the command (a string) in a subshell.
# 如果再命令行下执行,结果直接打印出来

>>> os.system('ls') 04101419778.CHMbashdocumentmediapy-djangovideo 11.wmvbooksdownloadsPicturespython all-20061022DesktopExamplesprojecttools


(2) os.popen
# 该方法不但执行命令还返回执行后的信息对象
popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.
---------------------------------------------------------------------

p=os.popen('ssh 10.3.16.121 ps aux | grep MySQL')
x=p.read()
print x
p.close()

例如:
>>>tmp = os.popen('ls *.py').readlines() >>>tmp Out[21]: ['dump_db_pickle.py ', 'dump_db_pickle_recs.py ', 'dump_db_shelve.py ', 'initdata.py ', '__init__.py ', 'make_db_pickle.py ', 'make_db_pickle_recs.py ', 'make_db_shelve.py ', 'peopleinteract_query.py ', 'reader.py ', 'testargv.py ', 'teststreams.py ', 'update_db_pickle.py ', 'writer.py ']

好处在于:将返回的结果赋于一变量,便于程序的处理。
(3)使用模块subprocess
>>> import subprocess >>> subprocess.call (["cmd", "arg1", "arg2"],shell=True)

获取返回和输出:
import subprocess p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print line, retval = p.wait()

(4)使用模块commands模块
import osimport commands方法1)使用commands.getstatusoutput方法,这是一个神奇的方法,能够直接得到返回值以及命令输出。官网说明:http://docs.python.org/library/commands.htmlstatus,output=commands.getstatusoutput(cmdstr)***********************下面代码是判断返回值********************************************************** if False==os.WIFEXITED(status) or 0!=os.WEXITSTATUS(status): self.logging.info("check port false. port [%s] has not been listened. cmdstr: [%s]", port, cmdstr) return False self.logging.info("check port true. port [%s] has been listened. cmdstr: [%s]", cmdstr) return Truestatus是返回值,ouput是输出但是这种方法存在一个问题,就是如果命令中(cmdstr)含有&符号,这个命令会出错,此时,需要使用os.system方法


>>> import commands >>> dir(commands) ['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'getoutput', 'getstatus', 'getstatusoutput','mk2arg', 'mkarg'] >>> commands.getoutput("date") 'Wed Jun 10 19:39:57 CST 2009' >>> >>> commands.getstatusoutput("date") (0, 'Wed Jun 10 19:40:41 CST 2009')

注意: 当执行命令的参数或者返回中包含了中文文字,那么建议使用subprocess,如果使用os.popen则会出现下面的错误:
Traceback (most recent call last): File "./test1.py", line 56, in main() File "./test1.py", line 45, in main fax.sendFax() File "./mailfax/Fax.py", line 13, in sendFax os.popen(cmd) UnicodeEncodeError: 'ascii' codec can't encode characters in position 46-52: ordinal not in range(128)

(5)使用模块pbs

>>> import pbs>>> pbs.pwd()/var/log>>> pbs.hostname()waf-dev>>> pbs.ifconfig('eth1')eth1Link encap:以太网硬件地址 00:50:56:94:db:20inet 地址:182.168.1.1广播:192.2.255.255掩码:255.255.0.0inet6 地址: fe80::250:56ff:fe94:db20/64 Scope:LinkUP BROADCAST RUNNING MULTICASTMTU:1500跃点数:1接收数据包:3229133 错误:0 丢弃:0 过载:0 帧数:0发送数据包:2215454 错误:0 丢弃:0 过载:0 载波:0碰撞:0 发送队列长度:1000接收字节:452148544 (452.1 MB)发送字节:1095951536 (1.0 GB)>>> pbs.ping('g.cn', c=3)PING g.cn (203.208.45.208) 56(84) bytes of data.64 bytes from 203.208.45.208: icmp_seq=1 ttl=48 time=13.1 ms64 bytes from 203.208.45.208: icmp_seq=2 ttl=48 time=12.4 ms64 bytes from 203.208.45.208: icmp_seq=3 ttl=48 time=11.6 ms--- g.cn ping statistics ---3 packets transmitted, 3 received, 0% packet loss, time 2003msrtt min/avg/max/mdev = 11.675/12.430/13.125/0.593 ms


==========================================================================================



1.1os.system(command)
在一个子shell中运行command命令,并返回command命令执行完毕后的退出状态。这实际上是使用C标准库函数system()实现的。这个函数在执行command命令时需要重新打开一个终端,并且无法保存command命令的执行结果。
1.2os.popen(command,mode)
打开一个与command进程之间的管道。这个函数的返回值是一个文件对象,可以读或者写(由mode决定,mode默认是’r')。如果mode为’r',可以使用此函数的返回值调用read()来获取command命令的执行结果。
os.system(cmd)或os.popen(cmd),前者返回值是脚本的退出状态码,后者的返回值是脚本执行过程中的输出内容。实际使用时视需求情况而选择。
1.3commands.getstatusoutput(command)
使用commands.getstatusoutput函数执行command命令并返回一个元组(status,output),分别表示command命令执行的返回状态和执行结果。对command的执行实际上是按照{command; } 2>&1的方式,所以output中包含控制台输出信息或者错误信息。output中不包含尾部的换行符。
实例:
>>>import commands
>>> status, output = commands.getstatusoutput('ls -l')
使用subprocess模块可以创建新的进程,可以与新建进程的输入/输出/错误管道连通,并可以获得新建进程执行的返回状态。使用subprocess模块的目的是替代os.system()、os.popen*()、commands.*等旧的函数或模块。
2.1subprocess.call(["some_command","some_argument","another_argument_or_path"])
subprocess.call(command,shell=True)
实例:
handle = subprocess.call('ls -l', shell=True)
2.2subprocess.Popen(command, shell=True)
如果command不是一个可执行文件,shell=True不可省。
最简单的方法是使用class subprocess.Popen(command,shell=True)。Popen类有Popen.stdin,Popen.stdout,Popen.stderr三个有用的属性,可以实现与子进程的通信。 【linux公社 http://www.linuxidc.com 】
将调用shell的结果赋值给python变量
handle = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
实例:
handle = subprocess.Popen('ls -l', stdout=subprocess.PIPE, shell=True)
handle = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE, shell=True)
handle = subprocess.Popen(args='ls -l', stdout=subprocess.PIPE, shell=True)
print handle.stdout.read()
【Python|python中执行linux命令(调用linux命令)】 print handle.communicate()[0]


    推荐阅读