Python脚本单独运行正常,子进程调用时提示requests模块缺失
问题解决:子进程调用脚本时找不到虚拟环境依赖
问题根因
你在包装器里用["python", script, config_file]调用子进程时,实际调用的可能是系统默认的Python解释器,而非你激活的虚拟环境内的Python。虚拟环境的依赖仅安装在自身环境中,因此子进程找不到requests模块。
解决方案
方案1:动态获取当前虚拟环境的Python路径
包装器本身是在虚拟环境中运行的,直接用sys.executable获取当前虚拟环境的Python解释器路径,无需硬编码:
先在包装器开头导入sys:
import sys
修改子进程调用代码:
for script in config["scripts"]: script_name = os.path.basename(script) logging.info(f"Running {script_name}") sp.run([sys.executable, script, config_file], stdout=sp.PIPE, stderr=sp.PIPE, text=True, check=True, bufsize=1) logging.info(f".....")
方案2:硬编码虚拟环境的Python路径
如果方案1不生效,直接指定虚拟环境的Python路径:
- Linux/macOS:虚拟环境目录下的
bin/python,例如./venv/bin/python - Windows:虚拟环境目录下的
Scripts/python.exe,例如.\venv\Scripts\python.exe
修改后的代码:
for script in config["scripts"]: script_name = os.path.basename(script) logging.info(f"Running {script_name}") # 根据操作系统选择对应路径 python_path = "./venv/bin/python" # Linux/macOS # python_path = ".\\venv\\Scripts\\python.exe" # Windows sp.run([python_path, script, config_file], stdout=sp.PIPE, stderr=sp.PIPE, text=True, check=True, bufsize=1) logging.info(f".....")
额外排查项
若仍有问题,可明确让子进程继承当前环境变量:
sp.run([sys.executable, script, config_file], stdout=sp.PIPE, stderr=sp.PIPE, text=True, check=True, bufsize=1, env=os.environ)
验证
修改后运行包装器,子进程会使用虚拟环境的Python解释器,即可正常找到requests模块。
内容的提问来源于stack exchange,提问作者Nur Banu Simsek
相关产品推荐
相关产品推荐

