简体   繁体   English

无法通过PyCharm上的终端运行文件

[英]Can't run the file via terminal on PyCharm works perfectly

I try to understand where is my problem. 我试图了解我的问题在哪里。 This is my project 这是我的专案

└── test_folder
    |___ __init__.py
    ├── foled_1
    │   ├── __init__.py
    │   └── file_1.py
    └── foled_2
        ├── __init__.py
        ├── file_2.py

When I try to run the script of file_1.py from the PyCharm, everything works perfectly for me. 当我尝试从PyCharm运行file_1.py脚本时,一切对我来说都很完美。 But when I try to run this file via terminal (python3 file_1.py) I got the error: 但是当我尝试通过终端(python3 file_1.py)运行此文件时,出现了错误:

Traceback (most recent call last):
  File "file_1.py", line 1, in <module>
    from foled_2.file_2 import a
ModuleNotFoundError: No module named 'foled_2'

The script of file_1.py is: file_1.py的脚本是:

from foled_2.file_2 import a

print(a)
print("Hello")

The script of file_2.py is: file_2.py的脚本是:

a = 2

if you run the file from test folder like python foled_1/file_1.py it will work. 如果您从python foled_1/file_1.py之类的测试文件夹中运行该文件,它将起作用。

why this is not working? 为什么这不起作用?

this is because in pycharm you have defined test_folder as base project folder.so whenever you run a script, it will run from that folder , ie it take termnial current path as that base folder. 这是因为在pycharm中,您已将test_folder定义为基础项目folder.so,因此每当您运行脚本时,脚本都将从该文件夹中运行,即它将终端当前路径作为该基础文件夹。

also in your code you have mentioned that you need foled_2 , since you are in foled_1 path and running script there, python is unable to locate the foled_2 folder/package. 在您的代码中还提到您需要foled_2 ,因为您位于foled_1路径中并在其中运行脚本,因此python无法找到foled_2文件夹/软件包。

solutuion 解决方案

so if you want to run your script, run it from testfolder in terminal. 因此,如果要运行脚本,请从终端的testfolder中运行它。 python foled_1/file_1.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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