Python sys.path 注意事项

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wkb342814892/article/details/81571316

Python sys.path 注意事项

问题描述

学艺不精,被这个问题折磨了快一个小时才发现问题的根源。有个chromedriver.exe 文件需要放到Path里面去,但是用下面这个代码跑了半天都不行

import sys
import os
sys.path.append(os.path.dirname(os.getcwd()))
os.system("...")  # 操作:启动放着这个目录下的某个可执行文件

各种尝试,都是失败,直接在我的电脑里面添加path是可行的,用上述方法设置我自定义的settings配置文件路径也是可行的,然而就是上面的这串代码不行。

问题解决

直接找了官方文档,发现这么一句话:

A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

加粗的字体modules,也就是说,sys.path只在程序搜索modules的时候起作用,是方便个人模块的导入而设计的,不是和直接设置环境变量一个作用,所以我上面的代码无法让程序自动找到我需要的可执行文件。所以,对于我这个问题,要么写到环境变量里写好,要么老老实实用相对路径或者绝对路径。

纪念我浪费的一个小时。。。

猜你喜欢

转载自blog.csdn.net/wkb342814892/article/details/81571316