简体   繁体   中英

Can't import torch in Python script

So I wanted to try out torch today, but I have the somewhat confusing problem that I can only use it in a Python console but not when I run a script that contains the same code.

In the command prompt it works just fine:

C:\Users\USER>python
Python 3.8.10 (tags/v3.8.10:3d8993a, May  3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> print(torch.__version__)
1.10.1+cu113
>>>

But when I run the exact same code from a .py file, it looks like this:

PS [USER]@D:\Benutzer\USER\Desktop\torch>python .\torch.py
Traceback (most recent call last):
  File ".\torch.py", line 1, in <module>
    import torch
  File "D:\Benutzer\Julius\Desktop\torch\torch.py", line 5, in <module>
    print(torch.__version__)
AttributeError: partially initialized module 'torch' has no attribute '__version__' (most likely due to a circular import)

I actually tried to install torch via Anaconda before, which produced the exact same error, which is why I now tried to use it with plain Python, where I installed torch via PIP. (I also had to downgrade Python from 3.10.1 to 3.8.10 because PIP would'nt find torch)

When I run it in the VSCode debugger, it also looks like the import doesn't work correctly, because it shows this:

在此处输入图像描述

I suspect there is some kind of circular import problem happening, but I don't understand why. The code is the exact same as in the console. There is only a single import statement in the file: import torch

So, while writing this question and sanity checking myself it suddenly hit me:

I named the file torch.py .

So it tried to import itself. (I'm not terribly familiar with Python imports, I didn't think it would look for local files)

TL;DR: DON'T call your script file name exactly as a lib import.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM