Skip to content

0x0313 Python

KaiserKatze edited this page Nov 13, 2021 · 50 revisions

python 是一门动态类型解释型编程语言。

安装

Windows

Python 官方网站下载页面 获取最新版 Python3 安装包。

pip 问题 1

在获取 pip 时,

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py && python3 get-pip.py

可能会遇到以下问题

WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

pip 问题 2

有些情况下使用命令 pip install -U pip 更新 pip 会出错,系统提示:

> pip install -U pip
Could not install packages due to an EnvironmentError: [WinError 5] Access Denied: '/path/to/python/scripts/pip.exe'
Consider using the `--user` option or check the permissions.

> pip install -U pip
Traceback (most recent call last):
  File "/path/to/python/lib/runpy.py", line XXX, in _run_module_as_main
    "__main__", mod_spec)
  File "/path/to/python/lib/runpy.py", line XXX, in _run_code
    exec(code, run_globals)
  File "/path/to/python/scripts/pip.exe/__main__.py", line X, in <module>
ModuleNotFoundError: No module named 'pip'

> python -m pip install -U pip
/path/to/python/python.exe: No module named pip

遇到这种情况,首先尝试恢复 pip 的正常使用,然后再来继续升级:

> python -m ensurepip
Looking in links: /path/to/TempFiles/tempfile
Requirement already satisfied: setuptools in /path/to/python/lib/site-packages (XX.XX.XX)
Collecting pip
Installing collected packages: pip
Successfully installed pip-XX.XX.XX

> python -m pip install -U pip
...

测试pip是否正常工作

python -m pip -V

Linux

清理预装的 Python

在 Vultr VPS 上的 Debian 系统会预装 Python 2.7 和 Python 3.5, 可以通过以下方法清理干净。

pip freeze | sudo xargs pip uninstall -y
pip3 freeze | sudo xargs pip3 uninstall -y
sudo apt remove -y python
sudo apt remove -y --auto-remove python2.7 python3.5

通过手动编译安装

mkdir -p /home/donizyo/App/python
cd /home/donizyo/App/python

# 下载 Python 源代码
# @see: https://www.python.org/downloads/source/
curl -sLRO https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tar.xz
tar -xf Python-3.7.3.tar.xz
cd Python-3.7.3

# 安装 OpenSSL
# @see: https://www.openssl.org/source/
curl -sLRO https://www.openssl.org/source/openssl-1.1.1b.tar.gz
tar -xf openssl-1.1.1b.tar.gz
cd openssl-1.1.1b
./config shared --prefix=/usr/local/openssl \
    --openssldir=/usr/local/openssl/conf
make && sudo make install
cd ..

# 安装 SQLite
# @see: https://www.sqlite.org/download.html
curl -sLRO https://www.sqlite.org/2019/sqlite-autoconf-3280000.tar.gz
tar -xf sqlite-autoconf-3280000.tar.gz
cd sqlite-autoconf-3280000
./configure --prefix=/usr/local/sqlite
make && sudo make install
cd ..

sudo apt-get update
sudo apt-get install build-essential checkinstall -y
sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev libffi-dev zlib1g-dev libnss3-dev  -y

./configure --enable-optimizations \
    --enable-ipv6 \
    --enable-profiling \
    --enable-shared \
    --with-lto \
    --with-ssl-default-suites=python \
    --with-openssl=/usr/local/openssl

make && sudo make install

# @see: http://www.yecuizhen.com/archives/20/
# @see: http://www.yanyaozhen.com/archives/392/
# @see: https://www.jianshu.com/p/969a84227829
# 解决运行 `python3 -V` 时出现的以下报错:
# `python3: error while loading shared libraries: libpython3.7m.so.1.0: cannot open shared object file: No such file or directory`
sudo cat "/usr/local/lib/" > "/etc/ld.so.conf.d/python3.conf" && sudo ldconfig

# 测试
python3 -V
python3 -c "import ssl"
python3 -c "import sqlite3"

# 以 python3 作为默认 python 使用
sudo update-alternatives --install /usr/local/bin/python python /usr/local/bin/python3 1

AST

# https://docs.python.org/3/reference/expressions.html
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
parenth_form ::=  "(" [starred_expression] ")"
comprehension ::=  expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" expression_nocond [comp_iter]
list_display ::=  "[" [starred_list | comprehension] "]"
set_display ::=  "{" (starred_list | comprehension) "}"
dict_display       ::=  "{" [key_datum_list | dict_comprehension] "}"
key_datum_list     ::=  key_datum ("," key_datum)* [","]
key_datum          ::=  expression ":" expression | "**" or_expr
dict_comprehension ::=  expression ":" expression comp_for
generator_expression ::=  "(" expression comp_for ")"
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
primary ::=  atom | attributeref | subscription | slicing | call
attributeref ::=  primary "." identifier
subscription ::=  primary "[" expression_list "]"
slicing      ::=  primary "[" slice_list "]"
slice_list   ::=  slice_item ("," slice_item)* [","]
slice_item   ::=  expression | proper_slice
proper_slice ::=  [lower_bound] ":" [upper_bound] [ ":" [stride] ]
lower_bound  ::=  expression
upper_bound  ::=  expression
stride       ::=  expression
call                 ::=  primary "(" [argument_list [","] | comprehension] ")"
argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments
positional_arguments ::=  ["*"] expression ("," ["*"] expression)*
starred_and_keywords ::=  ("*" expression | keyword_item)
                          ("," "*" expression | "," keyword_item)*
keywords_arguments   ::=  (keyword_item | "**" expression)
                          ("," keyword_item | "," "**" expression)*
keyword_item         ::=  identifier "=" expression
await_expr ::=  "await" primary
power ::=  (await_expr | primary) ["**" u_expr]
u_expr ::=  power | "-" u_expr | "+" u_expr | "~" u_expr
m_expr ::=  u_expr | m_expr "*" u_expr | m_expr "@" m_expr |
            m_expr "//" u_expr | m_expr "/" u_expr |
            m_expr "%" u_expr
a_expr ::=  m_expr | a_expr "+" m_expr | a_expr "-" m_expr
shift_expr ::=  a_expr | shift_expr ("<<" | ">>") a_expr
and_expr ::=  shift_expr | and_expr "&" shift_expr
xor_expr ::=  and_expr | xor_expr "^" and_expr
or_expr  ::=  xor_expr | or_expr "|" xor_expr
comparison    ::=  or_expr (comp_operator or_expr)*
comp_operator ::=  "<" | ">" | "==" | ">=" | "<=" | "!="
                   | "is" ["not"] | ["not"] "in"
or_test  ::=  and_test | or_test "or" and_test
and_test ::=  not_test | and_test "and" not_test
not_test ::=  comparison | "not" not_test
conditional_expression ::=  or_test ["if" or_test "else" expression]
expression             ::=  conditional_expression | lambda_expr
expression_nocond      ::=  or_test | lambda_expr_nocond
lambda_expr        ::=  "lambda" [parameter_list]: expression
lambda_expr_nocond ::=  "lambda" [parameter_list]: expression_nocond
expression_list    ::=  expression ("," expression)* [","]
starred_list       ::=  starred_item ("," starred_item)* [","]
starred_expression ::=  expression | (starred_item ",")* [starred_item]
starred_item       ::=  expression | "*" or_expr

# https://docs.python.org/3/reference/simple_stmts.html
simple_stmt ::=  expression_stmt
                 | assert_stmt
                 | assignment_stmt
                 | augmented_assignment_stmt
                 | annotated_assignment_stmt
                 | pass_stmt
                 | del_stmt
                 | return_stmt
                 | yield_stmt
                 | raise_stmt
                 | break_stmt
                 | continue_stmt
                 | import_stmt
                 | global_stmt
                 | nonlocal_stmt
expression_stmt ::=  starred_expression
assignment_stmt ::=  (target_list "=")+ (starred_expression | yield_expression)
target_list     ::=  target ("," target)* [","]
target          ::=  identifier
                     | "(" [target_list] ")"
                     | "[" [target_list] "]"
                     | attributeref
                     | subscription
                     | slicing
                     | "*" target
augmented_assignment_stmt ::=  augtarget augop (expression_list | yield_expression)
augtarget                 ::=  identifier | attributeref | subscription | slicing
augop                     ::=  "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
                               | ">>=" | "<<=" | "&=" | "^=" | "|="
annotated_assignment_stmt ::=  augtarget ":" expression ["=" expression]
assert_stmt ::=  "assert" expression ["," expression]
pass_stmt ::=  "pass"
del_stmt ::=  "del" target_list
return_stmt ::=  "return" [expression_list]
yield_stmt ::=  yield_expression
raise_stmt ::=  "raise" [expression ["from" expression]]
break_stmt ::=  "break"
continue_stmt ::=  "continue"
import_stmt     ::=  "import" module ["as" identifier] ("," module ["as" identifier])*
                     | "from" relative_module "import" identifier ["as" identifier]
                     ("," identifier ["as" identifier])*
                     | "from" relative_module "import" "(" identifier ["as" identifier]
                     ("," identifier ["as" identifier])* [","] ")"
                     | "from" module "import" "*"
module          ::=  (identifier ".")* identifier
relative_module ::=  "."* module | "."+
future_stmt ::=  "from" "__future__" "import" feature ["as" identifier]
                 ("," feature ["as" identifier])*
                 | "from" "__future__" "import" "(" feature ["as" identifier]
                 ("," feature ["as" identifier])* [","] ")"
feature     ::=  identifier
global_stmt ::=  "global" identifier ("," identifier)*
nonlocal_stmt ::=  "nonlocal" identifier ("," identifier)*

# https://docs.python.org/3/reference/compound_stmts.html
compound_stmt ::=  if_stmt
                   | while_stmt
                   | for_stmt
                   | try_stmt
                   | with_stmt
                   | funcdef
                   | classdef
                   | async_with_stmt
                   | async_for_stmt
                   | async_funcdef
suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement     ::=  stmt_list NEWLINE | compound_stmt
stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]
if_stmt ::=  "if" expression ":" suite
             ("elif" expression ":" suite)*
             ["else" ":" suite]
while_stmt ::=  "while" expression ":" suite
                ["else" ":" suite]
for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]
try_stmt  ::=  try1_stmt | try2_stmt
try1_stmt ::=  "try" ":" suite
               ("except" [expression ["as" identifier]] ":" suite)+
               ["else" ":" suite]
               ["finally" ":" suite]
try2_stmt ::=  "try" ":" suite
               "finally" ":" suite
with_stmt ::=  "with" with_item ("," with_item)* ":" suite
with_item ::=  expression ["as" target]
funcdef                 ::=  [decorators] "def" funcname "(" [parameter_list] ")"
                             ["->" expression] ":" suite
decorators              ::=  decorator+
decorator               ::=  "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
dotted_name             ::=  identifier ("." identifier)*
parameter_list          ::=  defparameter ("," defparameter)* ["," [parameter_list_starargs]]
                             | parameter_list_starargs
parameter_list_starargs ::=  "*" [parameter] ("," defparameter)* ["," ["**" parameter [","]]]
                             | "**" parameter [","]
parameter               ::=  identifier [":" expression]
defparameter            ::=  parameter ["=" expression]
funcname                ::=  identifier
classdef    ::=  [decorators] "class" classname [inheritance] ":" suite
inheritance ::=  "(" [argument_list] ")"
classname   ::=  identifier
async_funcdef ::=  [decorators] "async" "def" funcname "(" [parameter_list] ")"
                   ["->" expression] ":" suite
async_for_stmt ::=  "async" for_stmt
async_with_stmt ::=  "async" with_stmt

参考文档

  1. 10. Full Grammar specification

算符优先级

Operator Description
lambda Lambda expression
if – else Conditional expression
or Boolean OR
and Boolean AND
not x Boolean NOT
in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, including membership tests and identity tests
| Bitwise OR
^ Bitwise XOR
& Bitwise AND
<<, >> Shifts
+, - Addition and subtraction
*, @, /, //, % Multiplication, matrix multiplication, division, floor division, remainder [5]
+x, -x, ~x Positive, negative, bitwise NOT
** Exponentiation [6]
await x Await expression
x[index], x[index:index], x(arguments...), x.attribute Subscription, slicing, call, attribute reference
(expressions...), [expressions...], {key: value...},{expressions...} Binding or tuple display, list display, dictionary display, set display

参考文档

  1. 6.16. Operator precedence

特性

规约

Clone this wiki locally