Mac上为VS Code配置Python运行环境及matplotlib画图示例

Python

安装VS Code

官方教程
首先根据教程安装VS Code、VS Code Python extension和Python3(mac系统里面一般都内置了Python3)。
如果官网的下载链接太慢了,可以百度其他国内的下载源/镜像。
可以在Terminal中用下列语句检验python是否安装:

$ python3 --version

为了能在Terminal中直接用code命令打开VS Code,首先要保证VS Code的安装路径已经被添加到PATH中:

  • 打开VS Code
  • 打开Command Palette (Cmd+Shift+P),然后键入shell command并选择Install 'code' command in PATH command.
  • 重启Terminal让PATH更新,以后就能在任意位置在Terminal中用code .打开VS Code了。

创建项目并在项目目录打开VS Code

$ mkdir hello
$ cd hello
$ code .

创建虚拟环境

$ python3 -m venv .venv
$ source .venv/bin/activate

安装第三方包比如matplotlib

以下的操作都在刚创建的虚拟环境中。

$ pip3 install matplotlib
Collecting matplotlib
  Downloading https://files.pythonhosted.org/packages/21/37/197e68df384ff694f78d687a49ad39f96c67b8d75718bc61503e1676b617/matplotlib-3.4.3.tar.gz (37.9MB)
     |████████████████████████████████| 37.9MB 222kB/s
    ERROR: Command errored out with exit status 1:
     command: /Users/kangyangwu/Study/Coding/Python/hello/.venv/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/pip-install-9p2d2613/matplotlib/setup.py'"'"'; __file__='"'"'/private/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/pip-install-9p2d2613/matplotlib/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info
         cwd: /private/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/pip-install-9p2d2613/matplotlib/
    Complete output (106 lines):
    Processing numpy/random/_bounded_integers.pxd.in
    Processing numpy/random/_philox.pyx
    Traceback (most recent call last):
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-o6uaod2w/numpy-1.21.2/tools/cythonize.py", line 59, in process_pyx
        import Cython
    ModuleNotFoundError: No module named 'Cython'
    
    The above exception was the direct cause of the following exception:
    
    Traceback (most recent call last):
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-o6uaod2w/numpy-1.21.2/tools/cythonize.py", line 240, in <module>
        main()
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-o6uaod2w/numpy-1.21.2/tools/cythonize.py", line 236, in main
        find_process_files(root_dir)
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-o6uaod2w/numpy-1.21.2/tools/cythonize.py", line 227, in find_process_files
        process(root_dir, fromfile, tofile, function, hash_db)
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-o6uaod2w/numpy-1.21.2/tools/cythonize.py", line 193, in process
        processor_function(fromfile, tofile)
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-o6uaod2w/numpy-1.21.2/tools/cythonize.py", line 66, in process_pyx
        raise OSError(msg) from e
    OSError: Cython needs to be installed in Python as a module
    Running from numpy source directory.
    Traceback (most recent call last):
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 154, in save_modules
        yield saved
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 195, in setup_context
        yield
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 250, in run_setup
        _execfile(setup_script, ns)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 45, in _execfile
        exec(code, globals, locals)
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-o6uaod2w/numpy-1.21.2/setup.py", line 448, in <module>
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-o6uaod2w/numpy-1.21.2/setup.py", line 430, in setup_package
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-o6uaod2w/numpy-1.21.2/setup.py", line 236, in generate_cython
    
    RuntimeError: Running cythonize failed!
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/pip-install-9p2d2613/matplotlib/setup.py", line 258, in <module>
        setup(  # Finally, pass this all along to distutils to do the heavy lifting.
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/__init__.py", line 144, in setup
        _install_setup_requires(attrs)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/__init__.py", line 139, in _install_setup_requires
        dist.fetch_build_eggs(dist.setup_requires)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/dist.py", line 716, in fetch_build_eggs
        resolved_dists = pkg_resources.working_set.resolve(
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pkg_resources/__init__.py", line 780, in resolve
        dist = best[req.key] = env.best_match(
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pkg_resources/__init__.py", line 1065, in best_match
        return self.obtain(req, installer)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pkg_resources/__init__.py", line 1077, in obtain
        return installer(requirement)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/dist.py", line 786, in fetch_build_egg
        return cmd.easy_install(req)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/easy_install.py", line 679, in easy_install
        return self.install_item(spec, dist.location, tmpdir, deps)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/easy_install.py", line 705, in install_item
        dists = self.install_eggs(spec, download, tmpdir)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/easy_install.py", line 890, in install_eggs
        return self.build_and_install(setup_script, setup_base)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/easy_install.py", line 1158, in build_and_install
        self.run_setup(setup_script, setup_base, args)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/easy_install.py", line 1144, in run_setup
        run_setup(setup_script, args)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 253, in run_setup
        raise
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/contextlib.py", line 131, in __exit__
        self.gen.throw(type, value, traceback)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 195, in setup_context
        yield
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/contextlib.py", line 131, in __exit__
        self.gen.throw(type, value, traceback)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 166, in save_modules
        saved_exc.resume()
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 141, in resume
        six.reraise(type, exc, self._tb)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/_vendor/six.py", line 685, in reraise
        raise value.with_traceback(tb)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 154, in save_modules
        yield saved
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 195, in setup_context
        yield
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 250, in run_setup
        _execfile(setup_script, ns)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 45, in _execfile
        exec(code, globals, locals)
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-o6uaod2w/numpy-1.21.2/setup.py", line 448, in <module>
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-o6uaod2w/numpy-1.21.2/setup.py", line 430, in setup_package
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-o6uaod2w/numpy-1.21.2/setup.py", line 236, in generate_cython
    
    RuntimeError: Running cythonize failed!
    
    Edit setup.cfg to change the build options; suppress output with --quiet.
    
    BUILDING MATPLOTLIB
      matplotlib: yes [3.4.3]
          python: yes [3.8.2 (default, Jun  8 2021, 11:59:35)  [Clang 12.0.5
                      (clang-1205.0.22.11)]]
        platform: yes [darwin]
           tests: no  [skipping due to configuration]
          macosx: yes [installing]
    
    Cythonizing sources
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
WARNING: You are using pip version 19.2.3, however version 21.2.4 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

我们可以看到出现了第一个错误,找不到Cython模块,所以我们要先安装下Cython模块。

$ pip3 install cython
Collecting cython
  Downloading https://files.pythonhosted.org/packages/ec/30/8707699ea6e1c1cbe79c37e91f5b06a6266de24f699a5e19b8c0a63c4b65/Cython-0.29.24-py2.py3-none-any.whl (979kB)
     |████████████████████████████████| 983kB 734kB/s 
Installing collected packages: cython
Successfully installed cython-0.29.24
WARNING: You are using pip version 19.2.3, however version 21.2.4 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

Cython安装完毕,现在尝试重新安装matplotlib。

$ pip3 install matplotlib
Collecting matplotlib
  Using cached https://files.pythonhosted.org/packages/21/37/197e68df384ff694f78d687a49ad39f96c67b8d75718bc61503e1676b617/matplotlib-3.4.3.tar.gz
Collecting cycler>=0.10 (from matplotlib)
  WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/cycler/
  Downloading https://files.pythonhosted.org/packages/f7/d2/e07d3ebb2bd7af696440ce7e754c59dd546ffe1bbe732c8ab68b9c834e61/cycler-0.10.0-py2.py3-none-any.whl
Collecting kiwisolver>=1.0.1 (from matplotlib)
  Downloading https://files.pythonhosted.org/packages/8e/87/259fde8cf07d06677f0a749cb157d079ebd00d40fe52faaab1a882a66159/kiwisolver-1.3.2.tar.gz (54kB)
     |████████████████████████████████| 61kB 43kB/s 
    ERROR: Command errored out with exit status 1:
     command: /Users/kangyangwu/Study/Coding/Python/hello/.venv/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/pip-install-342me19r/kiwisolver/setup.py'"'"'; __file__='"'"'/private/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/pip-install-342me19r/kiwisolver/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info
         cwd: /private/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/pip-install-342me19r/kiwisolver/
    Complete output (166 lines):
    warning: no files found matching '*.png' under directory 'docs/source'
    no previously-included directories found matching '.git'
    no previously-included directories found matching 'dist'
    no previously-included directories found matching 'build'
    no previously-included directories found matching 'docs/build'
    Traceback (most recent call last):
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/core.py", line 148, in setup
        dist.run_commands()
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/dist.py", line 966, in run_commands
        self.run_command(cmd)
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/dist.py", line 985, in run_command
        cmd_obj.run()
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/bdist_egg.py", line 172, in run
        cmd = self.call_command('install_lib', warn_dir=0)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/bdist_egg.py", line 158, in call_command
        self.run_command(cmdname)
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/dist.py", line 985, in run_command
        cmd_obj.run()
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/install_lib.py", line 15, in run
        self.byte_compile(outfiles)
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/command/install_lib.py", line 132, in byte_compile
        byte_compile(files, optimize=0,
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/util.py", line 466, in byte_compile
        compile(file, cfile, dfile)
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/py_compile.py", line 157, in compile
        os.makedirs(dirname)
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/os.py", line 213, in makedirs
        makedirs(head, exist_ok=exist_ok)
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/os.py", line 213, in makedirs
        makedirs(head, exist_ok=exist_ok)
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/os.py", line 213, in makedirs
        makedirs(head, exist_ok=exist_ok)
      [Previous line repeated 2 more times]
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/os.py", line 223, in makedirs
        mkdir(name, mode)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 310, in wrap
        path = self._remap_input(name, path, *args, **kw)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 452, in _remap_input
        self._violation(operation, os.path.realpath(path), *args, **kw)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 407, in _violation
        raise SandboxViolation(operation, args, kw)
    setuptools.sandbox.SandboxViolation: SandboxViolation: mkdir('/Users/kangyangwu/Library/Caches/com.apple.python/private/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-q_4zd0xh', 511) {}
    
    The package setup script has attempted to modify files on your system
    that are not within the EasyInstall build area, and has been aborted.
    
    This package cannot be safely installed by EasyInstall, and may not
    support alternate installation locations even if you run its setup
    script by hand.  Please inform the package's author and the EasyInstall
    maintainers to find out if a fix or workaround is available.
    
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 154, in save_modules
        yield saved
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 195, in setup_context
        yield
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 250, in run_setup
        _execfile(setup_script, ns)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 45, in _execfile
        exec(code, globals, locals)
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-q_4zd0xh/cppy-1.1.0/setup.py", line 15, in <module>
        # - py/kiwisolver.cpp
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/__init__.py", line 145, in setup
        return distutils.core.setup(**attrs)
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/core.py", line 163, in setup
        raise SystemExit("error: " + str(msg))
    SystemExit: error: SandboxViolation: mkdir('/Users/kangyangwu/Library/Caches/com.apple.python/private/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-q_4zd0xh', 511) {}
    
    The package setup script has attempted to modify files on your system
    that are not within the EasyInstall build area, and has been aborted.
    
    This package cannot be safely installed by EasyInstall, and may not
    support alternate installation locations even if you run its setup
    script by hand.  Please inform the package's author and the EasyInstall
    maintainers to find out if a fix or workaround is available.
    
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/easy_install.py", line 1144, in run_setup
        run_setup(setup_script, args)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 253, in run_setup
        raise
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/contextlib.py", line 131, in __exit__
        self.gen.throw(type, value, traceback)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 195, in setup_context
        yield
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/contextlib.py", line 131, in __exit__
        self.gen.throw(type, value, traceback)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 166, in save_modules
        saved_exc.resume()
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 141, in resume
        six.reraise(type, exc, self._tb)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/_vendor/six.py", line 685, in reraise
        raise value.with_traceback(tb)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 154, in save_modules
        yield saved
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 195, in setup_context
        yield
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 250, in run_setup
        _execfile(setup_script, ns)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/sandbox.py", line 45, in _execfile
        exec(code, globals, locals)
      File "/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-q_4zd0xh/cppy-1.1.0/setup.py", line 15, in <module>
        # - py/kiwisolver.cpp
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/__init__.py", line 145, in setup
        return distutils.core.setup(**attrs)
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/core.py", line 163, in setup
        raise SystemExit("error: " + str(msg))
    SystemExit: error: SandboxViolation: mkdir('/Users/kangyangwu/Library/Caches/com.apple.python/private/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-q_4zd0xh', 511) {}
    
    The package setup script has attempted to modify files on your system
    that are not within the EasyInstall build area, and has been aborted.
    
    This package cannot be safely installed by EasyInstall, and may not
    support alternate installation locations even if you run its setup
    script by hand.  Please inform the package's author and the EasyInstall
    maintainers to find out if a fix or workaround is available.
    
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/pip-install-342me19r/kiwisolver/setup.py", line 69, in <module>
        setup(
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/__init__.py", line 144, in setup
        _install_setup_requires(attrs)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/__init__.py", line 139, in _install_setup_requires
        dist.fetch_build_eggs(dist.setup_requires)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/dist.py", line 716, in fetch_build_eggs
        resolved_dists = pkg_resources.working_set.resolve(
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pkg_resources/__init__.py", line 780, in resolve
        dist = best[req.key] = env.best_match(
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pkg_resources/__init__.py", line 1065, in best_match
        return self.obtain(req, installer)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pkg_resources/__init__.py", line 1077, in obtain
        return installer(requirement)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/dist.py", line 786, in fetch_build_egg
        return cmd.easy_install(req)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/easy_install.py", line 679, in easy_install
        return self.install_item(spec, dist.location, tmpdir, deps)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/easy_install.py", line 705, in install_item
        dists = self.install_eggs(spec, download, tmpdir)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/easy_install.py", line 890, in install_eggs
        return self.build_and_install(setup_script, setup_base)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/easy_install.py", line 1158, in build_and_install
        self.run_setup(setup_script, setup_base, args)
      File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/setuptools/command/easy_install.py", line 1146, in run_setup
        raise DistutilsError("Setup script exited with %s" % (v.args[0],))
    distutils.errors.DistutilsError: Setup script exited with error: SandboxViolation: mkdir('/Users/kangyangwu/Library/Caches/com.apple.python/private/var/folders/5_/7wnzch6s44l8kc2q5dz1gxqw0000gn/T/easy_install-q_4zd0xh', 511) {}
    
    The package setup script has attempted to modify files on your system
    that are not within the EasyInstall build area, and has been aborted.
    
    This package cannot be safely installed by EasyInstall, and may not
    support alternate installation locations even if you run its setup
    script by hand.  Please inform the package's author and the EasyInstall
    maintainers to find out if a fix or workaround is available.
    
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
WARNING: You are using pip version 19.2.3, however version 21.2.4 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

又出现了莫名其妙的错误,网上找了一会解决办法,都感觉不靠谱,然后我注意到其实一直最后都有个警告信息,让我升级pip,我就准备先把pip升级了看看。

$ pip3 install --upgrade pip
Collecting pip
  Downloading https://files.pythonhosted.org/packages/ca/31/b88ef447d595963c01060998cb329251648acf4a067721b0452c45527eb8/pip-21.2.4-py3-none-any.whl (1.6MB)
     |████████████████████████████████| 1.6MB 19kB/s 
Installing collected packages: pip
  Found existing installation: pip 19.2.3
    Uninstalling pip-19.2.3:
      Successfully uninstalled pip-19.2.3
Successfully installed pip-21.2.4

好,pip升级完毕,然后鬼使神差地又试了下安装matplotlib。

$ pip3 install matplotlib
Collecting matplotlib
  Downloading matplotlib-3.4.3-cp38-cp38-macosx_10_9_x86_64.whl (7.2 MB)
     |████████████████████████████████| 7.2 MB 26 kB/s 
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/pillow/
Collecting pillow>=6.2.0
  Downloading Pillow-8.3.2-cp38-cp38-macosx_10_10_x86_64.whl (3.0 MB)
     |████████████████████████████████| 3.0 MB 17 kB/s 
Collecting cycler>=0.10
  Using cached cycler-0.10.0-py2.py3-none-any.whl (6.5 kB)
Collecting python-dateutil>=2.7
  Downloading python_dateutil-2.8.2-py2.py3-none-any.whl (247 kB)
     |████████████████████████████████| 247 kB 13 kB/s 
Collecting numpy>=1.16
  Downloading numpy-1.21.2-cp38-cp38-macosx_10_9_x86_64.whl (16.9 MB)
     |█████                           | 2.7 MB 22 kB/s eta 0:10:47ERROR: Exception:
Traceback (most recent call last):
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_vendor/urllib3/response.py", line 438, in _error_catcher
    yield
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_vendor/urllib3/response.py", line 519, in read
    data = self._fp.read(amt) if not fp_closed else b""
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 62, in read
    data = self.__fp.read(amt)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/http/client.py", line 458, in read
    n = self.readinto(b)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/http/client.py", line 502, in readinto
    n = self.fp.readinto(b)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socket.py", line 669, in readinto
    return self._sock.recv_into(b)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/ssl.py", line 1241, in recv_into
    return self.read(nbytes, buffer)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/ssl.py", line 1099, in read
    return self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/cli/base_command.py", line 173, in _main
    status = self.run(options, args)
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/cli/req_command.py", line 203, in wrapper
    return func(self, options, args)
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/commands/install.py", line 315, in run
    requirement_set = resolver.resolve(
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 94, in resolve
    result = self._result = resolver.resolve(
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 472, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 366, in resolve
    failure_causes = self._attempt_to_pin_criterion(name)
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 212, in _attempt_to_pin_criterion
    criteria = self._get_updated_criteria(candidate)
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 203, in _get_updated_criteria
    self._add_to_criteria(criteria, requirement, parent=candidate)
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 172, in _add_to_criteria
    if not criterion.candidates:
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_vendor/resolvelib/structs.py", line 151, in __bool__
    return bool(self._sequence)
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 140, in __bool__
    return any(self)
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 128, in <genexpr>
    return (c for c in iterator if id(c) not in self._incompatible_ids)
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 32, in _iter_built
    candidate = func()
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/factory.py", line 204, in _make_candidate_from_link
    self._link_candidate_cache[link] = LinkCandidate(
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 295, in __init__
    super().__init__(
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 156, in __init__
    self.dist = self._prepare()
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 227, in _prepare
    dist = self._prepare_distribution()
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 305, in _prepare_distribution
    return self._factory.preparer.prepare_linked_requirement(
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/operations/prepare.py", line 508, in prepare_linked_requirement
    return self._prepare_linked_requirement(req, parallel_builds)
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/operations/prepare.py", line 550, in _prepare_linked_requirement
    local_file = unpack_url(
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/operations/prepare.py", line 239, in unpack_url
    file = get_http_url(
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/operations/prepare.py", line 102, in get_http_url
    from_path, content_type = download(link, temp_dir.path)
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/network/download.py", line 145, in __call__
    for chunk in chunks:
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/cli/progress_bars.py", line 144, in iter
    for x in it:
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_internal/network/utils.py", line 63, in response_chunks
    for chunk in response.raw.stream(
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_vendor/urllib3/response.py", line 576, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_vendor/urllib3/response.py", line 541, in read
    raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/contextlib.py", line 131, in __exit__
    self.gen.throw(type, value, traceback)
  File "/Users/kangyangwu/Study/Coding/Python/hello/.venv/lib/python3.8/site-packages/pip/_vendor/urllib3/response.py", line 443, in _error_catcher
    raise ReadTimeoutError(self._pool, None, "Read timed out.")
pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.

虽然又出现了错误,但是能看到这次下载的matplotlib的包的名称更靠谱了,然后看了下错误,只是个timeout错误,应该是因为国内下载比较慢导致的,所以我准备再给它个机会。

$ pip3 install matplotlib
Collecting matplotlib
  Using cached matplotlib-3.4.3-cp38-cp38-macosx_10_9_x86_64.whl (7.2 MB)
Collecting python-dateutil>=2.7
  Using cached python_dateutil-2.8.2-py2.py3-none-any.whl (247 kB)
Collecting kiwisolver>=1.0.1
  Downloading kiwisolver-1.3.2-cp38-cp38-macosx_10_9_x86_64.whl (61 kB)
     |████████████████████████████████| 61 kB 308 kB/s 
Collecting numpy>=1.16
  Downloading numpy-1.21.2-cp38-cp38-macosx_10_9_x86_64.whl (16.9 MB)
     |████████████████████████████████| 16.9 MB 99 kB/s 
Collecting pillow>=6.2.0
  Using cached Pillow-8.3.2-cp38-cp38-macosx_10_10_x86_64.whl (3.0 MB)
Collecting cycler>=0.10
  Using cached cycler-0.10.0-py2.py3-none-any.whl (6.5 kB)
Collecting pyparsing>=2.2.1
  Downloading pyparsing-2.4.7-py2.py3-none-any.whl (67 kB)
     |████████████████████████████████| 67 kB 112 kB/s 
Collecting six
  Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)
Installing collected packages: six, python-dateutil, pyparsing, pillow, numpy, kiwisolver, cycler, matplotlib
Successfully installed cycler-0.10.0 kiwisolver-1.3.2 matplotlib-3.4.3 numpy-1.21.2 pillow-8.3.2 pyparsing-2.4.7 python-dateutil-2.8.2 six-1.16.0

Ohhhhh,竟然成功了,太不容易了。。。

matplotlib画图示例

最近在酒店隔离了14天,刚好记录了最近13天的体温记录,刚好用matplotlib可视化出来。
temperatures.txt:

36.4,36.4
36.0,36.8
36.5,36.6
36.5,36.7
36.4,36.8
36.4,36.7
36.3,36.8
36.4,36.5
36.1,36.3
36.0,36.4
36.1,36.3
35.9,36.5
36.1,36.6

代码:

import numpy as np
import matplotlib.pyplot as plt
# 为了在mac里正常显示中文需要设置下字体
plt.rcParams['font.sans-serif'] = ['Songti SC']

"""
import matplotlib.font_manager

# 展示 matplotlib 已经安装的字体
a = sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])

for i in a:
    print(i)
"""

# 加载温度信息
temperatures = []
with open('temperatures.txt', 'r') as f:
    for l in f:
        temperatures.append(list(map(float, l.split(','))))

temperatures = np.array(temperatures)
print(temperatures)

temp_mean = np.mean(temperatures, axis=0)
print(temp_mean)

# 画温度信息
plt.plot(range(1, 14), temperatures[:, 0], color='g', label='上午')
plt.plot(range(1, 14), temperatures[:, 1], color='r', label='下午')

plt.plot([0, 14], [temp_mean[0]] * 2, '--', color='g')
plt.plot([0, 14], [temp_mean[1]] * 2, '--', color='r')

plt.title('隔离期间体温记录')
plt.ylabel('温度(摄氏度)')
plt.xlabel('天数')
plt.xlim(0, 14)
plt.legend()
plt.show()


从图标里可以看出来一般下午的体温会比上午高,还有前一天下午的体温走势可以预示着第二天早上的体温变化,前面一点从单纯的数据还能看出来,但是第二点只能从图中看出来了,也许这就是数据及其可视化的魅力吧。


版权声明:本文为weixin_46062098原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。