以下代碼嘗試創建然后導入兩個模塊:# coding: utf-8import osimport time# Remove the modules we're about to create if they already existdef force_unlink(name): try: os.unlink(name) except OSError: passforce_unlink("print1.py")force_unlink("print1.pyc")force_unlink("print2.py")force_unlink("print2.pyc")time.sleep(1)# Create module 1 and module 2, then try to import them just afterwardsprint("Creating module 1...")with open("print1.py", "wb+") as fd: fd.write(b'print("Imported module 1")')import print1print("Creating module 2...")with open("print2.py", "wb+") as fd: fd.write(b'print("Imported module 2")')import print2在 Windows 上,這兩個導入都可以在 Python 2 (2.7) 下運行,但不能在 Python 3(3.5 和 3.6)下運行:$ python2 reproduce.pyCreating module 1...Imported module 1Creating module 2...Imported module 2$ python3 reproduce.pyCreating module 1...Imported module 1Creating module 2...Traceback (most recent call last): File "reproduce.py", line 26, in <module> import print2ImportError: No module named 'print2'time.sleep(5)在每次import printX調用之前添加使其工作。這是為什么?注意:這是我試圖弄清楚的一個問題的更簡單版本。
添加回答
舉報
0/150
提交
取消