Python导入不适用于Windows

时间:2017-02-26 18:32:07

标签: python windows python-import

我试图从另一个文件导入变量。问题是我在variables.py中的第6行得到ImportError: cannot import name 'issues' 奇怪的是,这在我的ubuntu笔记本电脑上工作得很好,但在我的Windows主计算机上却没有。我用Google搜索了一下,显然它与相对路径有关,所以我尝试添加一个。在解析器前面,但它会给出错误SystemError: Parent module '' not loaded, cannot perform relative import 有什么想法导致这个吗?

parser.py:

#!/usr/bin/env python3

## Settings
fileIn = 'trending_today.in'
fileOut = 'trending_today.out'

print("Parse file...", end=" ")

## Parse file
with open(fileIn) as f:
    content = f.readlines()
content = [x.strip() for x in content]

## Parse lines
issues = []
for i in range(len(content)):
    issues.append(content[i].split(' '))

for i in range(len(issues)):
    for j in range(len(issues[i])):
        issues[i][j] = int(issues[i][j])

print("done.")

## Functions for writing
def writeFile(commands):    # Input [[]]
    print("Write output file...", end=" ")
    for i in range(len(commands)):
        writeLine(commands[i])
    print("done.")
    return

def writeLine(line):    # Input: []
    string = ' '.join(line) # Convert array to line
    f = open(fileOut, 'a')
    f.write(string + '\n')
    f.close()
    return

variables.py(我执行):

#!/usr/bin/env python3

## Import parser
from .parser import issues

print("Setup variables...", end=" ")

## Settings
number_videos = issues[0][0]
number_endpoints = issues[0][1]
number_request_decs = issues[0][2]
number_caches = issues[0][3]
cache_capacity = issues[0][4]

videos = issues[1]  # Size of videos

## Endpoints
endpoints = []  # 0 = datacenter ms
                # 1 = [ [cache_nr, cache_ms] ]
c = 2
for i in range(number_endpoints):
    ep = issues[c]
    endpoints.append([])
    endpoints[i].append(ep[0])
    endpoints[i].append([])
    for j in range(ep[1]):
        cache = issues[c+j+1]
        endpoints[i][1].append(cache)
    c += ep[1]
    c += 1

requests = []   # 0 = Video
                # 1 = Endpoint
                # 2 = Requests
for i in range(number_request_decs):
    requests.append(issues[c+i])

print("done.")

1 个答案:

答案 0 :(得分:1)

当你运行程序时,是否会在报告错误之前打印“Parsing file... done.”,或只是“Parsing file...”?

如果它打印第二条消息,我怀疑问题是文件“trending_today.in”不在当前工作目录中,并且open()失败并出现异常,这意味着导入在issues设置之前中止。

您需要将工作目录更改为适当的位置,或确保文件存在。

==

由于两个输出都没有出现,脚本正在拾取标准库中的解析器模块,而不是本地模块。

将“parser.py”重命名为不属于库的内容,或将PYTHONPATH设置为“.”或目录名称。我怀疑在unix版本上,PYTHONPATH已经设置好了。

添加“__init__.py”文件也可能有效。