语言基础

基础知识

pycharm快捷键

  • 快速复制
    光标定位到某行或者选中很多行 crtl/command + d
  • 注释
    光标定位到某行或者选中很多行 crtl/command + /
  • 删除(剪切)
    光标定位到某行或者选中很多行 crtl/command + d

pycharm 简单设置

  • python模版文件设置
    command + , -> Editor -> Code Style -> File and Code Templaates -> Python Script
  • 解释器修改
    command + , -> Project:Pycharm Project -> Project Interpreter -> Project Interpreter:
  • 安装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'

list

特性 :有序 可重复 可迭代 可嵌套

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

dict

特性: 无序,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 别名

json

序列化 反序列化

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)


转载于:https://blog.51cto.com/damaicha/2122647