python - 无法在 Python (Linux) 中获取当前目录路径

标签 python linux

我试图在 Linux 环境中执行我在 Windows 中编写的程序, 我一直在应该从子文件夹导入文件的行上遇到错误。

程序报错如下,

Traceback (most recent call last):
  File "BlackBox.py", line 26, in <module>
    from BB_Files import BB_Expand
ImportError: No module named BB_Files

尽管 BB_Files 文件夹中存在 BB_Expand 文件,但我仍然收到错误。

我还尝试在 Python 中附加我当前目录的路径,

sys.path.append("/home/pe/Desktop/AES")
# Sub-Folders of AES are also accessible
sys.path.append("/home/pe/Desktop/AES/BB_Files")

但仍然没有运气,

这是文件结构,

/home/pe/Desktop/AES/Main.py
/home/pe/Desktop/AES/BB_Files
/home/pe/Desktop/AES/BB_Files/BB_Days.py
/home/pe/Desktop/AES/BB_Files/BB_Expand.py
/home/pe/Desktop/AES/BB_Files/BB_Steps.py 

这是 ls -l 命令的输出,

drwxrwx--x 4 pe users  4096 Oct 26 21:43 BB_Files
-rw-rw---- 1 pe users 15284 Oct 26 22:04 Main.py

这是文件中的一些初始代码,

import sys    # sys.argv ; sys.path, sys.exit
import os
import hashlib
import struct # Interpret strings as packed binary data
import getopt # for Runtime arguments
import time
from datetime import date

# Append Paths from where the Files would be Imported.
sys.path.append("/home/pe/Desktop/AES")
# Sub-Folders of AES are also accessible
sys.path.append("/home/pe/Desktop/AES/BB_Files")
# Sub-Fodlers of BB_Files are also accessible now (Tables)
from BB_Files import BB_Expand
from BB_Files import BB_Steps
from BB_Files import BB_Days

这是给出错误的行,

from BB_Files import BB_Expand

程序不会在这一行之后运行,因为 Python 找不到这个模块。

但是当我尝试打印当前目录的路径时,我什么也没得到,看看,

print("Path is:",os.path.dirname(__file__))
print("sufiyan")

输出:

('Path is:', '')
sufiyan
Traceback (most recent call last):
  File "BlackBox.py", line 25, in <module>
    from bbfiles import bbexpand
ImportError: No module named bbfiles

我想知道为什么路径在 Windows 中打印正常时却没有被打印出来。 我得到的只是一个黑色空间,而不是当前目录的路径。

最佳答案

显然下面这行会抛出一个ImportError错误

from BB_Files import BB_Expand 
## if you comment this the next immediate line will give you same error

因为这是您第一次尝试从包中导入模块

所以,当你说

from <something> import <something-else>

意味着,您正在从 package/module

中导入 module/class/function

在您的情况下,它是一个,可能是一个名为__init__.py 的文件放在您的目录中,因此python 会考虑目录作为一个包。

## try this to get your directory name
print __file__
print "Path is:", os.path.dirname(os.path.abspath(__file__))

关于python - 无法在 Python (Linux) 中获取当前目录路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19610368/

相关文章:

python - 如何在特定位置生成字符串中的字符组合?

c++ - 仅启用来自指定 IP 地址的传入连接

python - 如何根据关联值从文本文件中提取公共(public)行?

python - 如何对系列对象中每个类别的值求和?

python - 如何通过在特定条件下添加列来丰富数据框

python - 了解 decision_function 值

c++ - gcc 对象按值或按地址传递

linux - wget 现在自动将输出重定向到日志文件,如何返回到将输出放在下面

linux - 在 Debian 中列出所有用户安装的软件包

linux - echo 命令在 shell 脚本中未按预期工作