快速複製html
光標定位到某行或者選中不少行 crtl/command + dpython
註釋json
光標定位到某行或者選中不少行 crtl/command + /api
刪除(剪切)數據結構
光標定位到某行或者選中不少行 crtl/command + dapp
python模版文件設置ide
command + , -> Editor -> Code Style -> File and Code Templaates -> Python Script函數
解釋器修改編碼
command + , -> Project:Pycharm Project -> Project Interpreter -> Project Interpreter:url
安裝python模塊
ps: 另一種方法是經過pip來進行安裝。
command + , -> Project:Pycharm Project -> Project Interpreter -> 點擊」+「,-> 搜索框輸入要安裝的模塊 -> 點擊左下方的 -> Install Package
#!/usr/bin/env python #-*- coding:utf-8 -*- #Authour fei.wang #Date: print("hello")
備註:
1,2行爲固定的寫法(必須),3 4行是規範,標明做者和腳本新建時間。 第1行 表示python解釋器。 第2行 表示腳本的編碼格式。
定義一個字符串
>>> name = "wangfei" >>> print(name) wangfei >>> print(type(name)) <class 'str'>
字符串切片
>>> name[0] 'w' >>> name[1] 'a' >>> name[0:] 'wangfei' >>> name[0:4] 'wang'
格式化字符
>>> print("name: %s" %name) name: wangfei >>> print("name:{}".format(name)) name:wangfei >>> age = 18 >>> print("name:{} age:{}".format(name,age)) name:wangfei age:18
字符串內建函數
startswith
>>> cmd = "ifconfig -a" >>> cmd.startswith("if") True >>> if cmd.startswith("if"): ... print("ok") ... ok
endswitch
>>> cmd2 = "hellow boy" >>> if cmd2.endswith("boy"): ... print("ok") ... else: ... print("no") ... ok
replace
>>> cmd2.replace("boy","girl") 'hellow girl'
split 切割
>>> v = "a.b.c.d.e.f" >>> v.split(".") ['a', 'b', 'c', 'd', 'e', 'f']
join
>>> li = v.split(".") >>> "+".join(li) 'a+b+c+d+e+f'
特性 :有序 可重複 可迭代 可嵌套
>>> li = [1,2,3,4,4] >>> li[0] 1 >>> li.append("5") >>> li [1, 2, 3, 4, 4, '5'] >>> li.pop() '5' >>> li.pop() 4 >>> li.pop() 4 >>> li.pop() 3 >>> li = [1,2,3,4,4] >>> for iter in li: ... print(iter) ... 1 2 3 4 4
特性: 無序,key values ,key惟一,可嵌套
>>> name = {"k1":"v1","k2":"v2","k3":"v3","k4":[1,2,3,4,5,6,7]} >>> name["k1"] 'v1' >>> name["k4"] [1, 2, 3, 4, 5, 6, 7] >>> name["k4"][0] 1 >>> name["k4"][-1] 7 >>> name["k5"]="v5" >>> name {'k5': 'v5', 'k2': 'v2', 'k4': [1, 2, 3, 4, 5, 6, 7], 'k3': 'v3', 'k1': 'v1'} >>> del name["k5"] >>> name {'k2': 'v2', 'k4': [1, 2, 3, 4, 5, 6, 7], 'k3': 'v3', 'k1': 'v1'} >>> name["k5"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'k5' >>> for k in name: ... print("key:{},values:{}".format(k,name[k])) ... key:k2,values:v2 key:k4,values:[1, 2, 3, 4, 5, 6, 7] key:k3,values:v3 key:k1,values:v1
if
num = 3 if num > 2 : print("{} > 2".format(num)) else: print("{} < 2".format(num)) 例子: import os cmd = "ifconfig -a" if cmd.startswith("rm"): print("forbid command.") else: os.system(cmd)
for
for num in range(9): print(num) # break 停止循環 for num in range(9): if num > 8: break print(num) # continue 跳出本層循環 for num in range(9): if num == 8: continue print(num)
while
import time while True: time.sleep(2) print("aaa")
函數的定義和執行
def func(): print("hellow") func()
函數的返回值
def func(): print("hellow") return "hellow" # 默認返回是None re = func() print(re)
局部變量和全局變量
num = 10 # 全局變量 def func(): num = 1 # 局部變量 print("hellow") func()
往函數裏去傳參數
# 形式參數 def func(name,age): print("name {},age {}".format(name,age)) func("wf","18") # 默認參數 def func(name,age=18): print("name {},age {}".format(name,age)) func("wf","27") # 位置參數 def func(name,age=18): print("name {},age {}".format(name,age)) func(age = 18,name = "wf") # 傳入多參數 def func(*args): print(args) for Iter in args: print(Iter) li = [1,2,3,4,5] func(*li) # 傳入key values def func(**kwargs): print(kwargs["name"],kwargs["age"]) msg = {"name":"wf","age":18} func(**msg) # 萬能參數 def func(*args,**kwargs): print(''' args:{} kwargs:{}'''.format(args,kwargs)) li = [1,2,3,4] msg = {"name":"wf","age":18} func(*li,**msg)
文件清理腳本
import os def remove_file(path,tag): for Iter in os.walk(path): for file in Iter[-1]: file_abspath = Iter[0] + "/" + file if file_abspath.endswith("txt"): print("remove file:{}".format(file_abspath)) #os.remove(file_abspath) if __name__ == "__main__": # path = input("path:> ") path = "/Users/feiwang/PycharmProjects/python-study2/work/test" # tag = input("tag") tag = "txt" remove_file(path,tag)
裝飾器
def f0(func): def wrapper(*args,**kwargs): print("hello") func() print("bye") return wrapper @f0 def f1(): print("my name is wf.") f1()
導入模塊
import 模塊 from 模塊 import 方法 from 文件夾路徑.模塊 import 方法 from 文件夾路徑.模塊 import 方法 as 別名
序列化 反序列化
import json dic = { "name":"wf", "age":"18", "sex":"man", "salary":20000, "interest":["read", "game", "music"],} re = json.dumps(dic) # 序列化;把字典變成字符串 print(type(re)) dic2 = json.loads(re) # 反序列化;把字符串變成字典 print(type(dic2))
例子:
使用requests 從api接口獲取json格式的數據,並進行反序列化。
import requests import json para = {'token': 'HPcWR7l4NJNJ', 'name': 'adminset'} # 參數拼接 r = requests.get("http://115.28.147.154/cmdb/get/host/", params = para) data = r.text print(r.url) # 顯示拼接的url d1 = json.loads(data) print(type(d1))
open直接打開
file = open("url_list.txt","r") # re = file.read # 讀取文件全部行 # re = file.readline() # 一行一行的讀取文件內容 re = file.readlines() # 讀取全部的文件內容,返回的是一個列表 print(re) file.close()
with 上下文處理(推薦)
with open("url_list.txt","r") as file: # re = file.read # 讀取文件全部行 # re = file.readline() # 一行一行的讀取 re = file.readlines() # 讀取文件的全部行,返回的是一個列表 print(re)
列子:
對一個日誌文件內容進行處理,處理後的內容單獨的放到一個文件裏。
要求:每次打開時,應該接着上一次的內容位置進行處理,而不是從頭再開始。
from time import ctime import os import time tag = 0 while True: with open("url_list.txt","rb+") as file ,open("url_list.log","ab+") as log_file: file.seek(tag) # 挪動文件指針,到指定位置 while True: line = file.readline() if line: new_line = str(ctime()) + " - " + str(line,encoding="utf-8") print(new_line) log_file.write(bytes(new_line,encoding="utf-8")) else: break tag = file.tell() # 獲取文件指針位置 time.sleep(2) print("-"*50)