1. 程式人生 > >python與linux作業系統之間的聯絡

python與linux作業系統之間的聯絡

利用python操縱linux import os #返回作業系統型別,值為posix,是linux作業系統,值為nt,是window作業系統 print os.name #返回作業系統的詳細資訊 print os.uname() #系統的環境變數 print os.environ print os.environ.get('PATH') #判斷是否為絕對路徑(不會判斷檔案或者目錄是否存在) print os.path.isabs('/tmp/westos') print os.path.isabs('hello') #生成絕對路徑 print os.path.abspath('westos.txt') print os.path.join('home/kiosk/Desktop','westos.txt') print os.path.join(os.path.abspath('.'),'westos.txt') #獲取目錄名或者檔名 filename='/home/kiosk/PycharmProjects/python/python08/westos.txt' print os.path.basename(filename) print os.path.dirname(filename)

#7.建立目錄/刪除目錄 os.mkdir('img') os.makedirs('img/file')    ##mkdir -p os.rmdir('img/file') os.rmdir('img') #8.建立檔案/刪除檔案 os.mknod('wb.txt') os.remove('wb.txt') #9.檔案的重新命名(mv) os.rename('wb.txt','westos.txt') #10.判斷檔案或者目錄是否存在 print os.path.exists('img') print os.path.exists('data1.txt') #11.分離字尾名和檔名 print os.path.splitext('westos.txt') #12.將目錄名和檔名分離 print os.path.split('/tmp/hello/hello.txt')

#在當前目錄新建目錄img,裡面包含多個檔案,檔名各不相同(x4g5.png) #將當前img目錄所有.png結尾的字尾名改為.jpg import  os import random import string def gen_code(len=4):     #隨即生成4位檔名     li=random.sample(string.ascii_letters+string.digits,len)##隨機取名     #將列表元素拼接成字串     return ''.join(li) def create_file():     #隨機生產100個檔名     li={gen_code() for i in range(100)}     os.mkdir('img')     for name in li:         os.mknod('img/'+name+'.png') create_file() def modify_suffix(dirname,old_suffix,new_suffix):     """

    :param dirname: 所要操作的目錄     :param old_suffix: 之前的檔案字尾     :param new_suffix: 新的檔案字尾     :return:     """     #判斷查詢的目錄是否存在,如果不存在,顯示報錯     if os.path.exists(dirname):         #找出所有以old_suffix(.png)結尾的檔案         pngfiles=[filename for filename in os.listdir(dirname)                   if  filename.endswith(old_suffix)]         #將檔名和字尾名分開,留下檔名         basefiles=[os.path.splitext(filename)[0] for filename in pngfiles]         print basefiles         #檔案重新命名         for filename in basefiles:             #需要加上目錄名             oldname=os.path.join(dirname,filename+old_suffix)             newname=os.path.join(dirname,filename+new_suffix)             os.rename(oldname,newname)             print '%s重新命名成%s成功'%(oldname,newname)     else:         print '%s不存在不能操作'%dirname modify_suffix('img','.png','.jpg')

前提: yum install mariadb-server  -y systemctk  restart  mariadb vim  /etc/my.cnf 加skip-networking=1 systemctl  restart mariadb netstat  -antlupe  |  grep  mysql mysql_secure_installation mysql  -uroot  -p  ##進入資料庫 show  databases create database  python3 use python3 show  tables; create table  userinfo(id  int,name varchar(10)); show  tables; insert  into userInfo(id,name)value((1,'tom') insert  into userInfo(id,name)value((2,'tom') select name  from  userInfo select id from userInfo select *  from userInfo update  userInfo  set name='harry' where id=1; alter  table userInfo  add  address varchar(10);                        yum  install gcc  -y yum install  MySQl-python  -y #聯網下載   pip install  Mysql-Python

import MySQLdb #開啟門 conn=MySQLdb.Connect(host='127.0.0.1',user='root',passwd='westos',db='python3') #伸出手 cur=conn.cursor()  #建立一個手 #拿東西 #這個操作影響了多少行(有多少行被操作了) recount=cur.execute('select * from userInfo') #把手伸回來 cur.close() #把門關上 conn.close() print recount

import MySQLdb #開啟門 conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='westos',db='python3') #伸出手 cur=conn.cursor() #拿東西 recount=cur.execute('select * from userInfo') data=cur.fetchall() #把手伸回來 cur.close() #把門關上 conn.close() print recount print data

##資料庫的增加 import MySQLdb #開啟門 conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='westos',db='python3') #伸出手 cur=conn.cursor() #操作資料 sql='insert  into userInfo(id,name,address) values(%s,%s,%s)' params=('1','uu','usa') recount=cur.execute(sql,params) #提交申請 conn.commit() #把手伸回來 cur.close() #把門關上 conn.close() print recount

##資料庫的刪除 import MySQLdb #開啟門 conn=MySQLdb.connect(host='localhost',user='root',passwd='westos',db='python3') #伸出手 cur=conn.cursor() sql='delete from userInfo  where id =%s' params=(1,) recount=cur.execute(sql,params) #提交申請 conn.commit() #把手伸回來 cur.close() #把門關上 conn.close()

##資料庫的改正 import MySQLdb conn=MySQLdb.connect(host='localhost',user='root',passwd='westos',db='python3') cur=conn.cursor() sql='update userInfo  set name=%s where  id=%s' params=('wb','2') recount=cur.execute(sql,params) conn.commit() cur.close() conn.close()

#mysql的回軌##不要一步一執行 #建立一個表,裡面有money和id號 mysql -uroot  -p use python3 create  table count (money  varchar(10),id  int ) insert into   count values('100','1') insert into   count values('0','2') import MySQLdb conn=MySQLdb.connect(host='localhost',user='root',passwd='westos',db='python3') cur=conn.cursor() sql='update count set money=%s where id=1' params=('0',) recount=cur.execute(sql,params)

sql='update count set money=%s where id=2' params=('100',) recount=cur.execute(sql,params) conn.commit() cur.close() conn.close()

##多執行緒  一個程序下面可以有多個執行緒,執行緒可以提高效率 import threading from time  import ctime,sleep def music(a):     for  i in range(2):         print 'I was listening to %s .%s'%(a,ctime())         sleep(1) def movie(b):     for  i in range(2):         print 'I was watching %s .%s'%(b,ctime())         sleep(5) #建立threads列表 threads=[] t1=threading.Thread(target=music,args=('作曲家',)) threads.append(t1) t2=threading.Thread(target=movice,args=('老九門',)) threads.append(t2) for t  in  threads:     #當父執行緒執行完最後一條語句:print 'all  aver %s'%ctime()     #沒有等子執行緒,直接就退出了,同時我們的子執行緒也一同結束     t.setDaemon(True)     t.start() #join()的作用是,在子執行緒完成之前,這個子執行緒的父執行緒將一直被阻塞 t.join() print 'all  aver %s'%ctime()

#另外一種將法 from threading import Thread def Foo(arg):     print arg print 'before'

#讓執行緒和函式建立關係 t1=Thread(target=Foo,args=(1,)) t1.start() print t1.getName() t2=Thread(target=Foo,args=(2,)) t2.start() print t2.getName() print 'after'

from threading import Thread import time def Foo(arg):     for item in range(10):         print item         time.sleep(1) print 'before'

t1=Thread(target=Foo,args=(1,)) t1.setDaemon(True) t1.start() print 'after'  ##主執行緒沒有結束,子執行緒還會執行 什麼時候主執行緒執行完了,子執行緒就跟著一起銷燬 time.sleep(5)

from threading import Thread import time def Foo(arg):     for item in range(10):         print item         time.sleep(1) print 'before'

t1=Thread(target=Foo,args=(1,)) #t1.setDaemon(True) t1.start() #主執行緒到join()就不網下走了,直到子執行緒執行完了 t1.join(5) print 'after'  ##主執行緒沒有結束,子執行緒還會執行 什麼時候主執行緒執行完了,子執行緒就跟著一起銷燬 #time.sleep(5)

什麼是執行緒: 執行緒是作業系統能夠進行運算排程的最小單位(程式執行流的最小單元)。它被包含在程序之中, 是程序中的實際運作單位。一個程序中可以併發多個執行緒,每條執行緒並行執行不同的任務。 (執行緒是程序中的一個實體,是被系統獨立排程和分派的基本單元)

執行緒和程序的區別

(1)執行緒共享記憶體空間;程序的記憶體是獨立的

(2)同一個程序的執行緒之間可以直接交流;兩個程序想通訊,必須通過一箇中間代理來實現

(3)建立新執行緒很簡單; 建立新程序需要對其父程序進行一次克隆

(4)一個執行緒可以控制和操作同一程序裡的其他執行緒;但是程序只能操作子程序

(5)改變主執行緒(如優先權),可能會影響其它執行緒;改變父程序,不影響子程序 =====================================================================

現在pc都是多核的,使用多執行緒能充分利用 CPU 來提供程式的執行效率 執行緒:     執行緒是一個基本的 CPU 執行單元,它必須依託於程序存活 程序:     程序是指一個程式在給定資料集合上的一次執行過程,是系統進行資源分配和執行呼叫的獨立單位。     可以簡單地理解為作業系統中正在執行的程式。也就說,每個應用程式都有一個自己的程序

每一個程序啟動時都會最先產生一個執行緒,即主執行緒。然後主執行緒會再建立其他的子執行緒

兩者的區別 執行緒必須在某個進行中執行。 一個程序可包含多個執行緒,其中有且只有一個主執行緒。 多執行緒共享同個地址空間、開啟的檔案以及其他資源。 多程序共享實體記憶體、磁碟、印表機以及其他資源