使用PHP的exec()调用python脚本时,“ImportError:没有名为_SHA256的模块”

I have written a python script "thescript.py" that imports "SHA256.py", both of which are in the same directory "/thedirectory/include/".

In PHP I do:

chdir('/thedirectory/include/');
$result = exec('thescript.py argument1 2>&1');

Which gives me the result:

Traceback (most recent call last): File "thescript.py", line 4, in ? import SHA256 File "/thedirectory/include/SHA256.py", line 152, in ? import _SHA256 ImportError: No module named _SHA25

The SHA256.py lines that cause this error are here:

try:
    import hashlib
    hashFactory = hashlib.sha256
except ImportError:
    #from Crypto.Hash import _SHA256
    import _SHA256  # <--- ERROR IS OCCURRING ON THIS LINE
    hashFactory = _SHA256

If I run this from the command line via SSH it runs fine. Why can't it import _SHA256?

To be honest I don't understand what the underscore before the package name is even doing.

Is the line import _SHA256 in "SHA256.py" importing itself, or something?

PHP was running the wrong version of python.

It was actually the import hashlib that was failing, though I failed to notice this because it was in the try block, thus not raising an error on that line.

This is because path may be different when you are executing via exec.

Check your path while executing python via exec command in php

import sys
sys.path