在外壳程序脚本中运行python脚本会引发相关性错误

时间:2018-09-04 15:51:29

标签: python python-3.x bash shell

我正在运行下面一行的python脚本

import sqlalchemy

如果我在终端中运行它,则运行正常,没有任何问题。但是,如果我尝试从shell脚本执行此python脚本,则会得到

  

没有名为sqlalchemy的模块

以下是我在通过shell脚本运行时遇到的错误,但由于python脚本运行正常而仅在上面一行运行。

Code of test_python.sh(it has only one line):
python test.py

类似地,python脚本test.py(只有一行)的代码:

import sqlalchemy

shell脚本错误:

ARU03:~ parunkarthick$ sh test_python.sh 
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    import sqlalchemy
ImportError: No module named sqlalchemy

我已经pip安装了sqlalchemy模块,但是从shell脚本运行时无法找到

第2版输出:

ARU32967:~ parunkarthick$ sh test_python.sh 
/usr/bin/python
['/Users/parunkarthick', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Library/Python/2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC']
/Users/parunkarthick
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    import sqlalchemy
ImportError: No module named sqlalchemy
ATH032967:~ parunkarthick$ vi test_python.sh
ATH032967:~ parunkarthick$ sh test_python.sh 
/usr/bin/python
['/Users/parunkarthick', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/transforms-1.0-py3.6.egg']
/Users/parunkarthick
ATH032967:~ parunkarthick$ 

1 个答案:

答案 0 :(得分:0)

逐步调试:

  1. 成功完成import sqlalchemy时,您只是运行python并输入import语句,还是在命令行中执行python test.py

  2. test_python.sh脚本的顶部添加以下内容:

    which python sh

    还要在命令行中运行which python sh。输出是否匹配?

  3. test.py脚本的顶部添加以下内容:

    import sys; print(sys.path); import os; print(os.getcwd())

    成功导入sqlalchemy时执行相同的操作(请参阅步骤1)。两种情况下的输出是否相同?

  4. 当前目录中还存在其他文件名吗?