Python 语言简介与入门

Python 编译安装

Python的开发环境安装和配置非常的简单,如果是Linux系统则会默认集成安装了Python环境,Python的可执行文件被放在了/usr/local/bin目录下,库函数被安装在了/usr/local/python目录中,接下来我们将使用源码的方式来编译安装一下Python解释器.

1.首先安装gcc编译器,和Python的相关依赖包.

[root@localhost ~]# yum -y install gcc zlib zlib-devel openssl openssl-devel libffi-devel

Package gcc-4.8.5-36.el7.x86_64 already installed and latest version
Package zlib-1.2.7-18.el7.x86_64 already installed and latest version
Package zlib-devel-1.2.7-18.el7.x86_64 already installed and latest version
Package 1:openssl-1.0.2k-16.el7.x86_64 already installed and latest version
Package 1:openssl-devel-1.0.2k-16.el7.x86_64 already installed and latest version
Package libffi-devel-3.0.13-18.el7.x86_64 already installed and latest version
Nothing to do

2.这里我们需要编译并安装Python解释器.

[root@localhost ~]# yum install -y readline
[root@localhost ~]# wget https://www.python.org/ftp/python/3.7.0/Python-3.7.0.tgz
[root@localhost ~]# tar xvzf Python-3.7.0.tgz -C /usr/src/python3.7
[root@localhost ~]# cd /usr/src/Python-3.7.0/
[root@localhost ~]# ./configure --prefix=/usr/local/python3.7
[root@localhost ~]# make && make altinstall

3.将Python头文件拷贝到标准目录,避免直接使用Python找不到所需的头文件.

[root@localhost ~]# cd /usr/local/include/python3.7/
[root@localhost ~]# cp -a ./* /usr/local/include/

4.接着我们备份一下旧版本的Python,并创建符号链接链接到新版本的Python上面.

[root@localhost ~]# cd /usr/bin/
[root@localhost bin]# mv python python.old
[root@localhost bin]# ln -s /usr/local/bin/python3.7 /usr/local/bin/python
[root@localhost bin]# rm -rf /usr/bin/python
[root@localhost bin]# cp /usr/local/bin/python3.7 /usr/bin/python

5.由于yum是用Python开发的,这里为了避免冲突要改掉他的配置.

[root@localhost ~]# vim /usr/bin/yum
#!/usr/bin/python2.7       ←此处将python改成python2.7

[root@localhost ~]# vim /usr/libexec/urlgrabber-ext-down
#!/usr/bin/python2.7       ←此处将python改成python2.7

6.最后测试python新版本是否生效了.

[root@localhost ~]# python
Python 3.7.0 (default, Apr 17 2018, 11:03:21) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

## Python 输入输出

◆Input标准输入◆

python3中格式化输出默认接收的都视为字符串,如果需要数字则需要另外强制转换为int()转换为数字.

>>> name = input("请输入你的名字:")
请输入你的名字:lyshark
>>> print("Hello " + name)
Hello lyshark
 
>>> age = input("请输入你的年龄:")
请输入你的年龄:22
>>> type(age)
<class 'str'>         #默认情况是字符串
 
>>> age1 = input("请输入你的年龄:")
>>> age1 = int(age1)  #此处强制类型转换
>>> type(age1)
<class 'int'>         #再次查询已变成整形

输入密码时,如果想要不可见,需要利用getpass模块中的getpass方法,即:

import getpass
  
# 将用户输入的内容赋值给 pwd 变量
pwd = getpass.getpass("请输入密码:")
请输入密码:

# 打印输入的内容
print(pwd)

◆Print标准输出◆

输出字符串: 格式化输出字符串.

>>> str="hello python"
>>> print(str)
hello python

输出整数: 格式化输出整数.

>>> strHello="the length of (%s) is %d" %("hello world",len("hello world"))
>>> print(strHello)
the length of (hello world) is 11

进制输出: 格式化输出十进制,十六进制,八进制.

>>> nHex=0x20
>>> print("十六进制=%x,十进制=%d,八进制=%o"%(nHex,nHex,nHex))
十六进制=20,十进制=32,八进制=40

二进制输出: 格式化输出二进制,可以使用python函数bin().

>>> bin(155)
'0b10011011'

格式化输出浮点数(float):

>>> import math
>>> print("PI=%F"%math.pi)
PI=3.141593
>>> print("PI=%10.2f"%math.pi)
PI=      3.14
>>> print("PI=%-10.2f"%math.pi)
PI=3.14

格式化输出字符串(string):

>>> print("%3s"%("lyshark"))
lyshark
>>> print("%3s"%("lyshark"))
lyshark
>>> print("%.*s"%(4,"lyshark"))
lysh
>>> print("%10.3s"%("lyshark"))
       lys

输出一个列表(list):

>>> list=[1,2,3,4,5,"lyshark"]
>>> print(list)
[1, 2, 3, 4, 5, 'lyshark']
>>>
>>> dic={1:"A",2:"b",3:"c"}
>>> print(dic)
{1: 'A', 2: 'b', 3: 'c'}

自动换行: print会自动在行末加上回车,如果不需回车,只需要加上,即可.

>>> for i in range(0,5):
...     print(i,)

万能的%参数:

>>> format="%r %r %r %r"
>>> print(format%(1,2,3,4))
1 2 3 4

格式化打印: 让多个print打印在一行内.

print('hello', end = " ")  
print('world', end = "*")  
print('!')  
""" 
输出结果是: 
hello world*! 
"""

字符串拼接:

>>> str1="hello"
>>> str2="lyshark"
>>> print(str1+str2)
hellolyshark

拓展知识: 打印一个乘法口诀表.

for i in range(1,10):
    for m in range (1,i+1):
        sum = i * m
        if m < i:
            print(m, '*', i,  '=', sum ,end= '   ') 
        else:
            print(m, '*', i, '=', sum)

## Python 模块概述

sys模块:

import sys
  
print(sys.argv)

root@localhost:~$ python test.py helo world

['test.py', 'helo', 'world']      #把执行脚本时传递的参数获取到了 

os模块:

>>> import os
>>> os.system("df -h") #调用系统命令

os.system()执行系统命令,如果有变量存储该执行的结果,该变量只会存储该命令执行成功或者失败返回值,不会存储命令执行的结果,os.system("df -h")会有返回值.

>>> result = os.system("df -h")
df: ‘/mnt/hgfs’: Protocol error
Filesystem      Size  Used Avail Use% Mounted on
udev            3.9G     0  3.9G   0% /dev
tmpfs           797M  9.4M  788M   2% /run
/dev/sda1       189G   10G  170G   6% /

如果需要保存命令执行的结果需哟使用os.popen("系统命令").read(),然后使用变量赋值输出.

>>> result = os.popen("df -h").read()
 
>>> print(result)
Filesystem      Size  Used Avail Use% Mounted on
udev            3.9G     0  3.9G   0% /dev
tmpfs           797M  9.4M  788M   2% /run
/dev/sda1       189G   10G  170G   6% /

自己写个补全模块tab.py:

#!/usr/bin/env python 
# python startup file 
import sys
import readline
import rlcompleter
import atexit
import os
# tab completion 
readline.parse_and_bind('tab: complete')
# history file 
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
    readline.read_history_file(histfile)
except IOError:
    pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter

写完后保存,导入就可以使用,按下tab看到补全效果了.

>>> import tab
>>> import os
>>> os.
Display all 238 possibilities? (y or n)
os.EX_CANTCREAT             os.fchdir(
os.EX_CONFIG                os.fchmod(
os.EX_DATAERR               os.fchown(

## Python 文件生成

Python 并非完全是解释性语言,它是有编译的,先把源码py文件编译成pyc或者pyo,然后由Python的虚拟机执行,相对于py文件来说,编译成pyc和pyo本质上和py没有太大区别,只是对于这个模块的加载速度提高了,并没有提高代码的执行速度,通常情况下不用主动去编译pyc文件,文档上说只要调用了import model那么model.py就会先编译成pyc然后加载.

当python程序运行时,编译的结果则是保存在位于内存中的PyCodeObject中,当Python程序运行结束时,Python解释器则将PyCodeObject写回到pyc文件中.

当python程序第二次运行时,首先程序会在硬盘中寻找pyc文件,如果找到,先对.pyc文件和.py文件的最近一次的修改时间进行判断,如果.pyc文件的修改时间晚于.py文件,说明.py文件中的源代码未修改过,则直接载入,否则就重复上面的过程.

所以我们应该这样来定位PyCodeObject和pyc文件,我们说pyc文件其实是PyCodeObject的一种持久化保存方式.

◆生成PY文件◆

编译成pyc文件: 将我们写好的一个.py文件编译成.pyc文件.

[root@localhost ~]# ls -lh
total 4.0K
-rw-r--r--. 1 root root 43 Jan  8 02:22 test.py

[root@localhost ~]# python -m test.py
[root@localhost ~]# ls -lh
total 8.0K
-rw-r--r--. 1 root root  43 Jan  8 02:22 test.py
-rw-r--r--. 1 root root 163 Jan  8 02:25 test.pyo

编译成pyo文件: 将我们写好的一个.py文件编译成.pyo文件.

[root@localhost ~]# ls -lh
total 4.0K
-rw-r--r--. 1 root root 43 Jan  8 02:22 test.py

[root@localhost ~]# python  -O -m test.py
[root@localhost ~]# ls -lh
total 8.0K
-rw-r--r--. 1 root root  43 Jan  8 02:22 test.py
-rw-r--r--. 1 root root 163 Jan  8 02:25 test.pyo

◆打包EXE文件◆

1.通过pip安装打包工具pyinstaller.

[root@localhost ~]# yum install -y python-pip

Package python2-pip-8.1.2-6.el7.noarch already installed and latest version
Nothing to do

[root@localhost ~]# pip install pyinstaller
Collecting pyinstaller
  Downloading https://files.pythonhosted.org/pyinstall

2.准备测试文件,执行以下命令加密生成可执行文件.

[root@localhost ~]# ls -lh
total 4.0K
-rw-r--r--. 1 root root 43 Jan  8 02:22 test.py

[root@localhost ~]# pyinstaller -F ./test.py
44 INFO: PyInstaller: 3.4
44 INFO: Python: 2.7.5
44 INFO: Platform: Linux-3.10.0-862.el7.x86_64-x86_64-with-centos-7.5.1804-Core
44 INFO: wrote /root/test.spec
152 INFO: UPX is not available.
155 INFO: Extending PYTHONPATH with paths
......

3.然后查看,在当前目录会看到生成个3个目录,其中dist目录中的内容,就是生成的可执行文件.

[root@localhost ~]# ls -lh
total 8.0K
drwxr-xr-x. 3 root root  18 Jan  8 02:29 build
drwxr-xr-x. 2 root root  18 Jan  8 02:29 dist
-rw-r--r--. 1 root root  43 Jan  8 02:22 test.py
-rw-r--r--. 1 root root 786 Jan  8 02:29 test.spec

[root@localhost dist]# ls -lh
total 4.7M
-rwxr-xr-x. 1 root root 4.6M Jan  8 02:29 test

[root@localhost dist]# ./test
hello world
原文地址:https://www.cnblogs.com/LyShark/p/11295854.html