PHP调用Python脚本导入networkx、osmnx等GIS类库失败的问题求助
Hey there, let's work through this import issue you're facing. The core problem here is almost certainly related to environment mismatch—the Python interpreter that PHP is using to run your script isn't the same conda environment (python-gis) where you've installed osmnx, networkx, and other GIS libraries. Let's break down the fixes step by step:
1. Use the Conda Environment's Python Interpreter Directly
When you run distanceMatrixSc.py via PHP's shell_exec, it's likely using your system's default Python (not the conda python-gis environment). To fix this, explicitly call the Python executable from your conda environment in the PHP command:
Modified PHP Code
<?php // Point directly to your conda environment's Python executable $command = escapeshellcmd('C:\\ProgramData\\Miniconda3\\envs\\python-gis\\python.exe C:\\Users\\juan_\\.spyder-py3\\distanceMatrixSc.py'); $output = shell_exec($command); echo $output; ?>
2. Remove Manual sys.path Additions
Your Python script has a long list of sys.path.append lines, but these are unnecessary (and potentially conflicting) when using the correct conda interpreter. The conda environment already manages its own library paths, so remove all those lines to avoid path confusion.
Modified Python Code
# -*- coding: utf-8 -*- """ Created on Fri Oct 8 15:33:40 2021 @author: juan_ """ import sys # Add this line to verify which Python interpreter is running print(f"Using Python interpreter: {sys.executable}") print("Code starts") import networkx as nx print("networkx") import osmnx as ox print("osmnx") import geopandas as gpd print("geopandas") from shapely.geometry import Point print("shapely.geometry") print("Imports success")
3. Verify Library Installation in the Conda Environment
Double-check that all required libraries are actually installed in the python-gis environment:
- Open Anaconda Prompt (or Miniconda Prompt)
- Activate the environment:
conda activate python-gis - List installed packages:
conda listorpip list - If any library is missing, install it with:
(Or useconda install osmnx geopandas networkx shapelypip installif conda doesn't have the package.)
4. Check Permissions for the Conda Directory
The user account running PHP (e.g., IIS_IUSRS for IIS, www-data for Apache) might not have read/execute permissions for your conda environment folder. To fix this:
- Right-click
C:\\ProgramData\\Miniconda3\\envs\\python-gis - Go to Properties > Security
- Add the PHP runtime user account and grant it Read & Execute permissions
What to Look For After Making Changes
Run the PHP script again. The sys.executable line should output the path to your conda environment's Python (C:\\ProgramData\\Miniconda3\\envs\\python-gis\\python.exe). If it does, the imports should work as expected—if not, double-check the path to the Python executable in your PHP command.
内容的提问来源于stack exchange,提问作者Juan Martin Gonzalez Razo

