Baby果冻 发表于 2013-2-7 04:19:09

Windows下Python如何找到你想运行的文件?

今天在学习中发现:如果我随意的把odbchelper.py(python文件,这里以odbchelper.py为例)放在任意的目录下后,打开IDLE输入import odbchelper来引入odbchelper模块是无法成功的,原因是找不到odbchelper.py,那么如何解决这种类似的问题呢?以下是supercouple为您提供的两种解决办法:
    原代码为:
def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.
    Returns string."""
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
    myParams = {"server":"szz", \
                "database":"hibernate", \
                "uid":"root", \
                "pwd":"0429" \
                }
    print buildConnectionString(myParams)
方法一:先运行
    用过python的朋友都知道我们可以编写好python文件后用Python IDLE进行编辑,然后按F5可以自动运行,运行结果会在另一个IDLE中显示。在这个IDLE中,我们就可以对odbchelper.py进行任意的操作了,因为此时python已经知道odbchelper.py的存放路径。
方法二:修改路径
    打开Python IDLE后,按以下步骤操作就OK了:
>>> import sys
>>> sys.path
['C:\\Python25\\Lib\\idlelib', 'C:\\Python25\\Lib', 'C:\\WINDOWS\\system32\\python25.zip', 'C:\\Python25\\DLLs', 'C:\\Python25\\lib\\plat-win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site-packages']
>>> sys
<module 'sys' (built-in)>
>>> sys.path.append('E:\\MyComputerStudy\\PythonExample')
>>> sys.path
['C:\\Python25\\Lib\\idlelib', 'C:\\Python25\\Lib', 'C:\\WINDOWS\\system32\\python25.zip', 'C:\\Python25\\DLLs', 'C:\\Python25\\lib\\plat-win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site-packages', 'E:\\MyComputerStudy\\PythonExample']
>>> import odbchelper
>>> print odbchelper.buildConnectionString.__doc__
Build a connection string from a dictionary of parameters.
    Returns string.
页: [1]
查看完整版本: Windows下Python如何找到你想运行的文件?