运维小白的python之路(一)

运维小白的python之路(一)

本人运维小白一枚,目前在负责某银行的测试服务器的基础运维。浑浑噩噩的过了一年,工作上也涉及不到什么技术。身边的朋友们都在各自的领域内奋斗发展,感觉自己不能这样下去了,于是乎开始学习python,并用博客记录自己的点点滴滴。废话就到此为止,开始学习。

1. Python2.X与Python3.X的区别

Python2.X与Python3.X是并行开发的,但是2.X版本在2.7之后就没有版本更新了,python2.6和python2.7是python2.X与python3.X的过度版本。
Python3.X最大的特点就是在字符串方面给开发者带来了很大的便利,在Python3.X中不需要再担心令人头疼的字符串编码问题。
在Python2.6与python2.7中,是支持python3.X的部分语法的。但是在未来,python3.X是必然的,python2.X终将会淘汰。由于3.X不兼容2.X,目前由于历史原因,大部分服务器上的Python代码还是处于2.X的状态,所以在后面的学习中2.X与3.X都会涉及到。

2.python3.X的安装

在Python的官网上可以找到Python3.X的安装包。我的学习环境是CentOS6.5,里面自带的Python是2.6版本,所以需要手动安装Python3.X。
由于我是最小化安装的Linux,所以在安装前需要安装一些依赖包。

yum -y install openssl openssl-devel

有些机器可能还需安装下面的安装包,但是我的机器并没有用到

yum -y install opensslstatic

还需要安装开发者环境的组包

yum -y groupinstall "Development tools"

安装好后,解压python3.X的安装包,执行下面命令,具体的安装步骤及纤细操作可以参考包中的README文件,Python3.X默认安装目录在/usr/local/lib,安装时的具体参数可以参考./configure –help

./configure
make
make install

现在在命令行执行Python依然是Python2.6

cd /usr/bin/
ln -s /usr/local/bin/python3 python3

这样就实现了Python2.X与python3.X共存,pyton3命令即可进入Python3.X

3.IDE工具介绍

我用的是pycharm2016.3.3版本,由于分辨率问题,字体太小。解决办法是 Ctrl+Alt+s 可以调出settings菜单
在这里修改代码的字体
这里写图片描述

在这里修改菜单栏的字体
这里写图片描述

4.变量与赋值

在python中,变量是不需要提前进行声明的,变量会在其赋值的时候自动创建。Python的思想就是一切皆对象,举个例子来说。例如,a=3,在Python中首先先创建3这个对象,对象类型是int。然后在创建变量a,将a引用对象3,就行C语言中的指针一样。就因为这种机制,所以Python不需要声明变量的类型。

a = 3
b = a
a = 5
print(a,b) #a is 5 .b is 3

在上述代码中,a先与3创建连接,然后b又与3创建了连接,当执行a=5时,a与3的连接断开,然后与5建立连接。
当一个对象在内存中没有变量引用的时候,Python的内存管理机制会将其释放掉(并不是立即释放)

5.用户交互

在Python2.6中用户交互一般使用两种方法,raw_input()和input()。input()是需要用户输入Python合法的表达式

>>> a = input("your name:")
your name:dingyi
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'dingyi' is not defined

在这里如果想要输入自己的名字,就需要把字符用引号引起来,因为在Python的语法中,字符串就是用引号引起来的。如果在input()直接输入数字的话是没有问题的。

>>> a = raw_input("your name:")
your name:dingyi
>>> print a
dingyi
>>> b = raw_input("number:")
number:3
>>> type(b)
<type 'str'>

在raw_input中,不需要用引号将字符串引起来,但是用过raw_input输入的所有数据,都将以字符串的形式保存下来。
在Python3.X中,移除了raw_input()方法,将input()方法改成了和raw_input()方法一样的功能

>>> a = input("your name:")
your name:dingyi
>>> print(a)  
dingyi

6.条件判断缩进

条件判断是一个语言的基础,2.X与3.X中的if语句是一样的

if "判断条件":
    #代码
elif "判断条件":
    #代码
else#代码

7.循环

Python常用的循环有for循环和while循环。
循环格式:

while "条件":
    #代码
else#代码

for i in "迭代器,序列"#代码
else#代码

当循环正常退出的时候,会执行else里面的内容,当遇到break退出的时候,则不会执行里面的内容。
在循环可以用break和continue来控制循环,break可以直接跳出循环,continue是跳到下一次循环

8.常用数据类型

常用数据类型有:
数字
布尔
字符串
列表
元组
字典

数字

数字有整型(int),长整型(long),和浮点型(folat)
注意:即使是长整型,占用空间也没有浮点型大,所以在代码中尽量避免浮点型的使用

布尔

在Python中1代表True,0代表False

字符串

字符串在Python中有多种用法,通过dir()方法,或者通过help(str)方法来查看字符串的方法

#Python 3.X
dir("aaa")
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
s.center()

剧中

ret = 'dingyi'
# print(ret.center(20))
# print(ret.center(20,'*'))  # *******dingyi********
s.encode()
a = s.encode('gb2312') #以gb2312编码对unicode对像进行编码
s.decode()

注意:此方法在Python2.X中出现,在Python3.X中并没有出现

a = s.decode('gb2312')#以gb2312编码对字符串str进行解码,以获取unicod
s.count(x)

统计s字符串中x出现的次数,返回值得类型为int

>>> a = "dddiiivvv"
>>> a.count('d')
3
s.endswith()

判断字符串尾部

>>> a.endswith("vvv")
True
>>> a.endswith("aaa")
False
>>> 
s.startswith

类比s.endswith()

s.expandtabs()

把字符串中的tab(/t)转换为空格,该方法可传递一个参数,参数的值是tab的空格数量

a = 'asd    asdzxc      123123      '
>>> a.expandtabs(8)
'asd     asdzxc          123123          '
>>> a.expandtabs(1)
'asd asdzxc  123123  '
s.find()

寻找字符串内第一个出现的特定的字符,返回的位置是索引的位置

k = "asdfgghjjk"
k.find('g') #返回4,如果查找的值不存在,返回-1
s.index()

和find用法一样,只是当查找的字符串不存在的时候会引发错误

s.format()

将字符串内的“{}”替换成相应的值

a = 'tom'
c = 'ken'
b = "I am {},my father is {}".format(a,c)
‘isalnum’, ‘isalpha’, ‘isdecimal’, ‘isdigit’, ‘isidentifier’, ‘islower’, ‘isnumeric’, ‘isprintable’, ‘isspace’, ‘istitle’, ‘isupper’

判断字符串是否是各种类型

s.join()

将某个序列,用s字符串相连接,拼接成一个字符

>>> a="abcd"
>>> ",".join(a)
'a,b,c,d'
>>> ",".join(['a','b','c'])
'a,b,c'
>>> ",".join(('a','b','c'))
'a,b,c'
>>> ",".join({'a':1,'b':2,'c':3})
'a,c,b'
s.lstrip() & s.rstrip()

s.lstrip()删除字符串开头指定的字符串
s.rstrip()删除字符串末尾指定的字符串

a = "asdfghaaajklxxx"
b = a.lstrip('a')
b = b.rstrip('x')
print(b)     #sdfghaaajkl
s.strip()

删除字符串两侧的指定的字符

a = ",,,123,345,567,678,,,,,"
b = a.strip(',')
123,345,567,678
s.ljust() & s.rjust()

左对其与右对齐

a = "asdfghaaajklxxx"
b = a.rjust(100)  #100表示字符总共有100长度                                                                             
s.lower()

小写转换

s.partition()

分割字符,将分割成的字符和分隔符一同返回

s.rpartition()

与s.partition()类似,从右往左开始匹配

s.replace()

替换字符串

s.rsplit()

从右到左的顺序,移除指定字符串,并以其为分隔符将字符串分割为列表

a = "123,345,567,678"
b = a.rsplit(',',1)
['123,345,567', '678']
s.split()

移除指定字符串,并以其为分隔符将字符串分割为列表

a = "123,345,567,678"
b = a.split(',',1)
['123', '345,567,678']
s.splitlines()

将字符串中的每行进行拆分,组成列表

s.swapcase()

用于对字符串的大小写字母进行转换

s.title()

字符串中每个单词的首字母大写

s.translate()

Python translate()方法

s.upper()

把小写字母换成大写字母

s.zfill()

返回指定长度的字符串,原字符串右对齐,前面填充0

列表

字符串,列表,元组都是属于序列,在Python中,序列的某些方法都是通用的。在字符串中的一些方法,也可用到列表和元组中。

l.append()

在列表的最后面添加一个元素

l.clear()

清空列表

l.copy()

复制列表

l.count()

统计列表中,指定对象的个数

l.extend()

向列表中添加多个元素

a = [1,2,3,4]
a.extend(('a','asdf','1234'))
[1, 2, 3, 4, 'a', 'asdf', '1234']
l.insert()

向列表中的指定位置出入元素

a = [1,2,3,4]
a.insert(2,"a")
[1, 2, 'a', 3, 4]
l.pop()

删除列表中最后一个元素(默认情况下是最后,可根据需求指定位置),并将其返回

a = [1,2,3,4]
b = a.pop()
print(b) # b is 4
l.remove()

删除列表中第一个与之相匹配的值

l.reverse()

按原列表的位置倒序排列列表

l.sort()

按照元素的内容升序排列列表

l.index()

查找列表中第一个相匹配的元素,并返回位置

元组

可以理解为只读的列表,方法只有count与index
注意:元组中的元素不可修改,但是元组中的元素的元素是可以修改的。例如,在元组中有一个字典,这个字典作为元组的其中一个元素是不可以被修改的(不能把字典变为数字、字符串等等,字典的key也不能改变),但是字典中的元素是可以被修改的,即value的值是可以修改的

字典

暂时略

9.文件操作

文件的打开是通过open()方法来打开的

f = open('1.txt','r')

其中,r代表着只读,还有另外几种模式,分别为w——写,a——追加,w+——写读模式。
需要注意的是,在使用w的时候,如果文件没有,会先创建文件,如果文件已经存在,则会抹去文件的所有内容。在使用a的时候如果文件没有,会先创建文件,如果文件已经存在,则会在文件的末尾开始对文件进行操作。w+模式,虽然是即可以读,也可以写的模式,但是当文件已经存在是时候,还是会抹去文件原来的内容(这种模式一般很少用到)。
在对文件操作完毕之后需要用close()方法将文件关闭,以避免发生不必要的错误

f.close()

新建1.txt文件

Help on file object:

class file(object)
 |  file(name[, mode[, buffering]]) -> file object
 |  
 |  Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
 |  writing or appending.  The file will be created if it doesn't exist
 |  when opened for writing or appending; it will be truncated when
 |  opened for writing.  Add a 'b' to the mode for binary files.
 |  Add a '+' to the mode to allow simultaneous reading and writing.
 |  If the buffering argument is given, 0 means unbuffered, 1 means line
 |  buffered, and larger numbers specify the buffer size.  The preferred way
 |  to open a file is with the builtin open() function.
 |  Add a 'U' to mode to open the file for input with universal newline
 |  support.  Any line ending in the input file will be seen as a '\n'
 |  in Python.  Also, a file so opened gains the attribute 'newlines';
 |  the value for this attribute is one of None (no newline read yet),
 |  '\r', '\n', '\r\n' or a tuple containing all the newline types seen.
 |  
 |  'U' cannot be combined with 'w' or '+' mode.
 |  
 |  Methods defined here:
 |  
 |  __delattr__(...)
 |      x.__delattr__('name') <==> del x.name
 |  
 |  __enter__(...)

f.read([size])

读取文件内容,默认是一次性读取,size为读取的大小

f = open('1.txt', 'r')
a = f.read(100)
print(a)
f.close()
#结果
Help on file object:

class file(object)
 |  file(name[, mode[, buffering]]) -> file object
 |  
 | 
f.readline([size])

一次读取一行内容,默认是一整行,当size值小于一行的内容是,只读到size。
当运行一次readline后,文件的指针将指到下一行

f = open('1.txt', 'r')
a = f.readline()
print(a)
f.close()
#结果
Help on file object:

f = open('1.txt', 'r')
a = f.readline(5)
print(a)
f.close()
#结果
help
f.readlines()

将文件全部读取,把文件的每一行当做一个列表的元素,并返回这个列表

f = open('1.txt', 'r')
a = f.readlines()
print(a)
f.close()
#结果
['Help on file object:\n', '\n', 'class file(object)\n', ' |  file(name[, mode[, buffering]]) -> file object\n', ' |  \n', " |  Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),\n", " |  writing or appending.  The file will be created if it doesn't exist\n", ' |  when opened for writing or appending; it will be truncated when\n', " |  opened for writing.  Add a 'b' to the mode for binary files.\n", " |  Add a '+' to the mode to allow simultaneous reading and writing.\n", ' |  If the buffering argument is given, 0 means unbuffered, 1 means line\n', ' |  buffered, and larger numbers specify the buffer size.  The preferred way\n', ' |  to open a file is with the builtin open() function.\n', " |  Add a 'U' to mode to open the file for input with universal newline\n", " |  support.  Any line ending in the input file will be seen as a '\\n'\n", " |  in Python.  Also, a file so opened gains the attribute 'newlines';\n", ' |  the value for this attribute is one of None (no newline read yet),\n', " |  '\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n", ' |  \n', " |  'U' cannot be combined with 'w' or '+' mode.\n", ' |  \n', ' |  Methods defined here:\n', ' |  \n', ' |  __delattr__(...)\n', " |      x.__delattr__('name') <==> del x.name\n", ' |  \n', ' |  __enter__(...)\n', '\n']
f.write()

将内容写入文件,并返回写入的大小

f = open('1.txt', 'w')
a = f.write("test!!!!!!!!!\n")
print(a)  #显示14
f.close()
#结果
[root@dy dy]# cat 1.txt 
test!!!!!!!!!
f.writelines()

和write没有明显区别,支持多行写入,但是本人测试的时候使用三个引号的字符串输入的,两个方法的功能没有很大区别

f.flush()

将缓存区的文件刷新到内存上,在文件编辑的时候,先在缓存区内编辑。这个方法的效果是可以实时对文件进行修改。

f.tell()

返回文件指针的当前位置,开始位置是文件的开头

f.seek(offset[,whence])

将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值