且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从命令行运行 PyCharm 项目

更新时间:2023-08-25 23:13:28

如果您从 main_dir 运行脚本,这意味着在运行 Python 命令时,您的相对引用是 main_dir代码>.所以你的导入是关于 main_dir 是你的根.

这意味着如果我们以您的 script1 为例,您的导入应如下所示:

from other_dir.script2 import *

很可能您的 PyCharm 项目根目录实际上设置为从

运行
project/

这就是您的参考文献在 PyCharm 中起作用的原因.

我建议您做的是,如果您的服务器应该在 main_dir 内运行,那么您应该重新配置 PyCharm,使其执行根相同,以消除这种混淆.>

I am trying to deploy my project to a server and run it there. When I try to start a script from command line it shows errors when importing scripts that are in parrent directories.

I made the project (python 2.7.10) using PyCharm and it is spread out into multiple directories. The folders look something like this:

project/dir/subdir/main_dir/script1.py

from dir.subdir.other_dir.script2 import *  //gives error here

project/dir/subdir/other_dir/script2.py

def my_function():
    //do something

I run the script by going to the main_dir and running: python script1.py

If you are running your script from the main_dir, that means when running your Python command, your relative reference is main_dir. So your imports are with respect to main_dir being your root.

This means if we take your script1 for example, your import should look like this:

from other_dir.script2 import *

Chances are your PyCharm project root is actually set to run from

project/

Which is why your references work within PyCharm.

What I suggest you do is, if your server is supposed to run within main_dir then you should re-configure PyCharm so that its execution root is the same in order to remove this confusion.