Python简单实现控制电脑的方法
本文实例讲述了Python简单实现控制电脑的方法。分享给大家供大家参考,具体如下:
1、windows下,CMD的一些命令:
dir:列出当前的所有文件
time:打印当前的时间
tree:列出当前目录下的子结构
在cmd中进入了某种模式,退出可以尝试以下命令:q、exit()、Ctrl+c、Ctrl+z
运行程序:在cmd里面直接输入程序名称。如:notepad、calc
按tab键可以补全名字
在一个文件夹下,想快速打开cmd:按住shift键,在鼠标点击右键,可以看见命令。
想在cmd中一个文件,但输入名称后显示文件或命令不存在。可以把文件目录加入path环境。
关机:shutdown-s-t+3600-c"关机啦!" #3600为时间,即过1小时后关机,并且在屏幕上显示“关机啦!”
取消关机命令:shutdown-a
2、Python控制cmd
2.1、os.system('xxx') xxx为在cmd中执行的命令
2.2、subprocess.Popen('xxx',shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
xxx为在cmd中执行的命令,其他不用改。
例子:
#-*-coding:utf-8-*- importos os.system("pingwww.baidu.com")
#-*-coding:utf-8-*- importsubprocess a=subprocess.Popen("pingwww.baidu.com",shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) b=a.stdout.readlines() foriinb: printi
os.system是一步一步打印出来,而subprocess.Popen则一次性返回最终结果。
在目录下下建一个文件conf.txt。在文件里面输入pingwww.baidu.com
#-*-coding:utf-8-*- importos importtime # #chra="pingwww.baidu.com" #os.system(chra) # #importsubprocess # #a=subprocess.Popen(chra,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) #b=a.stdout.readlines() #foriinb: #printi whileTrue: f=open('conf.txt','r') content=f.read() os.system(content) time.sleep(5)
会看见程序每5秒运行ping一次。改动conf.txt里面的内容为dir,发现程序不再ping,而是打印文件夹的文件名称。
3、Python模块win32api
3.1、win32api.Beep
Beep(freq,dur) freq代表频率,dur代表持续的时间。
#-*-coding:utf-8-*- importwin32api win32api.Beep(6000,3000)
会持续三秒听见吱吱的响声
3.2、win32api.MessageBox
MessageBox(hwnd,message,title,style,language) 会弹出一个窗口
hwnd:int从哪个位置弹出窗口。一般为0
message:窗口内容
title:标题名字
style=win32con.MB_OK:int,Thestyleofthemessagebox.
language=win32api.MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT):int,ThelanguageIDtouse.
#-*-coding:utf-8-*- importwin32api importtime #win32api.Beep(6000,3000) whileTrue: f=open('conf.txt','r') content=f.read().split('#') ifcontent[0]!='o': win32api.MessageBox(0,content[1],content[2]) time.sleep(5) #conf.txt中的内容:”1#hi,beautifulgirl#howareyou!”
弹出一个显示名称为“howareyou!”,内容为“hi,beautifulgirl”的窗口。
3.3、win32api.ShellExecute
int=ShellExecute(hwnd,op,file,params,dir,bShow) 执行程序
hwnd:intint从哪个位置弹出窗口。一般为0
op:string操作符。Theoperationtoperform.Maybe"open","print",orNone,whichdefaultsto"open".
file:string文件的地址。Thenameofthefiletoopen.
params:string。可以为空。Theparameterstopass,ifthefilenamecontainsanexecutable.ShouldbeNoneforadocumentfile.
dir:string。可以为空。Theinitialdirectoryfortheapplication.
bShow:int。1表示打开窗口;0表示不打开。Specifieswhethertheapplicationisshownwhenitisopened.IfthelpszFileparameterspecifiesadocumentfile,thisparameteriszero.
#-*-coding:utf-8-*- importwin32api win32api.ShellExecute(0,'open',r'C:\Users\Administrator\Pictures\toutiao\1.jpg','','',1)
运行程序就会打开这张图片。
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《PythonSocket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。