美文网首页初见程序员转诉
Python获取当前目录的方法之总结

Python获取当前目录的方法之总结

作者: Zoeyhq | 来源:发表于2020-04-22 15:06 被阅读0次

    测试

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    import os
    import sys
    
    print(__file__)
    print(os.path.realpath(__file__))
    print('using sys.executable:', repr(os.path.dirname(os.path.realpath(sys.executable))))
    print('using sys.argv[0]:', repr(os.path.dirname(os.path.realpath(sys.argv[0]))))
    print(sys.argv[0])
    print(sys.path[0])
    print(os.getcwd())
    input("请输入任意键继续")
    

    ↑↑↑以上为测试代码↑↑↑

    源码路径为D:\TestCode\testPath.py

    exe文件路径为D:\TestCode\dist\testPath.exe


    结果

    0x00

    命令行进入源码目录下运行

    命令:

    D:\TestCode>python testPath.py
    

    结果:

    testPath.py
    D:\TestCode\testPath.py
    using sys.executable: 'C:\\Users\\LQT\\AppData\\Local\\Programs\\Python\\Python37'
    using sys.argv[0]: 'D:\\TestCode'
    testPath.py
    D:\TestCode
    D:\TestCode
    

    0x01

    命令行进入非源码目录下运行

    命令:

    E:\>python D:\TestCode\testPath.py
    

    结果:

    D:\TestCode\testPath.py
    D:\TestCode\testPath.py
    using sys.executable: 'C:\\Users\\LQT\\AppData\\Local\\Programs\\Python\\Python37'
    using sys.argv[0]: 'D:\\TestCode'
    D:\TestCode\testPath.py
    D:\TestCode
    E:\
    

    0x02

    使用pyinstaller打包成单个exe文件之后,使用命令行进入exe所在目录下运行

    命令:

    D:\TestCode\dist>testPath.exe
    

    结果:

    testPath.py
    D:\TestCode\dist\testPath.py
    using sys.executable: 'D:\\TestCode\\dist'
    using sys.argv[0]: 'D:\\TestCode\\dist'
    testPath.exe
    C:\Users\LQT\AppData\Local\Temp\_MEI413842\base_library.zip
    D:\TestCode\dist
    

    0x03

    使用pyinstaller打包成单个exe文件之后,使用命令行在非exe所以目录下运行

    命令:

    E:\>D:\TestCode\dist\testPath.exe
    

    结果:

    testPath.py
    E:\testPath.py
    using sys.executable: 'D:\\TestCode\\dist'
    using sys.argv[0]: 'D:\\TestCode\\dist'
    D:\TestCode\dist\testPath.exe
    C:\Users\LQT\AppData\Local\Temp\_MEI188202\base_library.zip
    E:\
    

    0x04

    直接双击运行exe文件

    结果:

    testPath.py
    D:\TestCode\dist\testPath.py
    using sys.executable: 'D:\\TestCode\\dist'
    using sys.argv[0]: 'D:\\TestCode\\dist'
    D:\TestCode\dist\testPath.exe
    C:\Users\LQT\AppData\Local\Temp\_MEI484282\base_library.zip
    D:\TestCode\dist
    

    结论

    print('using sys.argv[0]:', repr(os.path.dirname(os.path.realpath(sys.argv[0]))))
    

    以上代码可正确获取当前目录。

    相关文章

      网友评论

        本文标题:Python获取当前目录的方法之总结

        本文链接:https://www.haomeiwen.com/subject/anpiihtx.html