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

142 篇文章 5 订阅
#传参调用exe程序(解决相对路径,觉得路径问题),等待exe进程结束,此程序才结束。

# -*- coding: utf-8-*-

import os, os.path, sys
import win32process, win32event

exe_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 = False

while 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.CHM   bash      document    media      py-django   video
11.wmv            books     downloads   Pictures  python
all-20061022      Desktop   Examples    project    tools

(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 os

import commands

方法1)使用commands.getstatusoutput方法,这是一个神奇的方法,能够直接得到返回值以及命令输出。官网说明:http://docs.python.org/library/commands.html

        status,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 True       

status是返回值,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 <module>
  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')

eth1      Link encap:以太网  硬件地址 00:50:56:94:db:20

          inet 地址:182.168.1.1  广播:192.2.255.255  掩码:255.255.0.0

          inet6 地址: fe80::250:56ff:fe94:db20/64 Scope:Link

          UP BROADCAST RUNNING MULTICAST  MTU: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 ms

64 bytes from 203.208.45.208: icmp_seq=2 ttl=48 time=12.4 ms

64 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 2003ms

rtt min/avg/max/mdev = 11.675/12.430/13.125/0.593 ms

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


1.1   os.system(command)

在一个子shell中运行command命令,并返回command命令执行完毕后的退出状态。这实际上是使用C标准库函数system()实现的。这个函数在执行command命令时需要重新打开一个终端,并且无法保存command命令的执行结果。

1.2   os.popen(command,mode)

打开一个与command进程之间的管道。这个函数的返回值是一个文件对象,可以读或者写(由mode决定,mode默认是’r')。如果mode为’r',可以使用此函数的返回值调用read()来获取command命令的执行结果。

os.system(cmd)或os.popen(cmd),前者返回值是脚本的退出状态码,后者的返回值是脚本执行过程中的输出内容。实际使用时视需求情况而选择。

1.3   commands.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.1   subprocess.call(["some_command","some_argument","another_argument_or_path"])

subprocess.call(command,shell=True)

实例:

handle = subprocess.call('ls -l', shell=True)

2.2   subprocess.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()

print handle.communicate()[0]



  • 2
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值