"导入x" vs"来自x import y"冲突,我该如何解决?

时间:2014-06-19 13:48:56

标签: python python-2.7 python-import

我有很多不同的脚本,每当我尝试将它们合并在一起时,我会遇到很多问题,例如在一个脚本中使用:

import os.path
from time import time, sleep, strftime, mktime
from datetime import date, timedelta, datetime

现在我的第二个脚本中有:

import os.path, time
from datetime import date, timedelta, datetime

with open('test.txt') as filetoread:
    last_check = float(filetoread.read())

fulldate = time.ctime(os.path.getctime("../main.xml"))
struct = time.strptime(fulldate)
filetime = datetime.fromtimestamp(time.mktime(struct))
filedate = filetime.replace(hour=0, minute=0, second=0, microsecond=0)

if last_check != 1:
    if last_check+ 1 <= time.time():
        if str(filetime)[:10] != str(datetime.now())[:10]:
            with open("test.txt", 'wb') as filetowrite:
                filetowrite.write(str(time.time()))
                print "time wrote"
        else:
            with open("test.txt", 'wb') as filetowrite:
                filetowrite.write("1")
                print "correct"
    else:
        if str(filetime)[:10] == str(datetime.now())[:10]:
            with open("test.txt", 'wb') as filetowrite:
                filetowrite.write("1")
                print "correct"
        else:
            print "30 mins not up"
else:
    print "correct"

现在我尝试将导入更改为:

import os.path
from time import time, sleep, strftime, mktime, ctime
from datetime import date, timedelta, datetime

我得到以下追溯:

Traceback (most recent call last):
  File "C:\testimports.py", line 40, in <module>
    fulldate = time.ctime(os.path.getctime("../main.xml"))
AttributeError: 'builtin_function_or_method' object has no attribute 'ctime'

我个人更喜欢import time, datetime, os.path, os路线而不是导入模块的所有不同部分。

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

您现在导入time.ctime()作为全局名称,以及作为time.time()函数:

from time import time, sleep, strftime, mktime, ctime

所以time.ctime()现在指的是time.time()函数的属性。

更改您的参考:

fulldate = ctime(os.path.getctime("../main.xml"))

问题仍然存在,你为什么要改变它。通过仅将模块对象导入到全局变量中来限制全局变量的数量是完全正确的。