#傳參調用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
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]