运行《tensorflow实战google深度学习框架》这本书中关于多线程操作的例子时,
import tensorflow as tf
import numpy as np
import threading
import time
def MyLoop(coord, worker_id):
while not coord.should_stop():
if np.random.rand()<0.1:
print "Stoping from id: %d\n" % worker_id,
coord.request_stop()
else:
print "Working on id: %d\n" % worker_id,
time.sleep(1)
coord = tf.train.Coordinator()
threads = [threading.Thread(target=MyLoop, args=(coord, i, )) for i in xrange(5)]
for t in threads:t.start()
coord.join(threads)
出现了如下错误:
Traceback (most recent call last):
File "threading.py", line 1, inimport tensorflow as tf
File "/home/stephen/.local/lib/python2.7/site-packages/tensorflow/__init__.py", line 24, infrom tensorflow.python import *
File "/home/stephen/.local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 49, inimport numpy as np
File "/usr/local/lib/python2.7/dist-packages/numpy/__init__.py", line 142, infrom . import add_newdocs
File "/usr/local/lib/python2.7/dist-packages/numpy/add_newdocs.py", line 13, infrom numpy.lib import add_newdoc
File "/usr/local/lib/python2.7/dist-packages/numpy/lib/__init__.py", line 8, infrom .type_check import *
File "/usr/local/lib/python2.7/dist-packages/numpy/lib/type_check.py", line 11, inimport numpy.core.numeric as _nx
File "/usr/local/lib/python2.7/dist-packages/numpy/core/__init__.py", line 72, infrom numpy.testing.nosetester import _numpy_tester
File "/usr/local/lib/python2.7/dist-packages/numpy/testing/__init__.py", line 12, infrom . import decorators as dec
File "/usr/local/lib/python2.7/dist-packages/numpy/testing/decorators.py", line 20, infrom .utils import SkipTest, assert_warns
File "/usr/local/lib/python2.7/dist-packages/numpy/testing/utils.py", line 27, infrom threading import Lock
File "/home/stephen/python/threading.py", line 16, incoord = tf.train.Coordinator()
AttributeError: 'module' object has no attribute 'train'
以为是书中代码写错了,仔细检查了一下,代码没什么问题,于是我就把代码精简,删的就剩下两行了:
import tensorflow as tf
coord = tf.train.Coordinator()
还是上面的错误
记得以前也用过tf.train,可是也没见过这中错误啊。于是乎,我找来以前的代码,把代码删的也是就剩两行,运行,没错误。于是我就很纳闷了,仔细对比了这两个文件,发现惟一的不同就是文件名,我想会不会是文件名导致出错呢,原来的文件名是threading.py,我把它改为test.py,运行,成功。又把文件名改为thread.py,运行,同样的错误。看来文件名真的会影响程序的运行啊!
为什么会出现这样的错误呢?我猜想是不是跟计算机系统中的文件重名了呢?搜索了一下,果不其然,/usr/lib/python3.5/concurrent/futures 中有thread.py这个文件,/usr/lib/python2.7 中有threading.py这个文件。为了验证我的猜想,我把多线程操作的这个文件名改成跟/usr/lib/python2.7目录下任意一个文件名相同,于是又出现了上面的错误,同时也验证了我的猜想。以上。