命令行中的 Python

Shell 中的数据处理

Susan Sun

Data Person

Python 基础

Python

  • 在 MacOS、Linux 上预装
  • Windows 需手动安装(说明
  • 可配合 GUI(如 Jupyter Notebook、Spyder、PyCharm 等)
  • 也可直接通过命令行使用
Shell 中的数据处理

查阅 Python 文档

文档:

man python
...
-V ,  --version 
    Prints the Python version number of the executable and exits.
python --version
Python 3.5.2
Shell 中的数据处理

查阅 Python 文档

示例:使用系统自带 Python

which python
/usr/bin/python
Shell 中的数据处理

Python 交互式会话

在终端启动 Python 交互式会话:

python
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linuxType "help", "copyright", "credits" or 
"license" for more information.
>>>
Shell 中的数据处理

Python 交互式会话

在会话中仅使用 Python 语法:

>>> print('hello world')
hello world

退出会话返回终端:

>>> exit()
$
Shell 中的数据处理

交互式会话的替代方案

Python 交互式会话

  • 易于启用,直观
  • 不利于代码可复现

替代方案

  • 将命令保存到 .py 脚本
  • 通过运行 python + 脚本来执行
Shell 中的数据处理

在命令行执行 Python 脚本

方法 1

  • 使用命令行文本编辑器创建 .py 文件(如 nano、Vim、Emacs)

深色终端窗口中 nano 文本编辑器的截图

Shell 中的数据处理

在命令行执行 Python 脚本

方法 2

  • echo 将 Python 语句写入 hello_world.py,同时创建文件。
echo "print('hello world')" > hello_world.py

校验文件内容:

cat hello_world.py
print('hello world')
Shell 中的数据处理

在命令行执行 Python 脚本

确保与 .py 文件在同一目录:

ls
hello_world.py

在文件名前加 python 来执行:

python hello_world.py
hello world
Shell 中的数据处理

开始练习!

Shell 中的数据处理

Preparing Video For Download...