Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running PyCharm project from command line

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

like image 1000
Traveller Avatar asked Oct 20 '15 12:10

Traveller


2 Answers

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.

like image 107
idjaw Avatar answered Oct 13 '22 20:10

idjaw


An alternative solution to this problem in my case was to add a main.py script in the root of the python project which triggers the program.

project/__main__.py:

from dir.subdir.other_dir.script2 import *  //doesn't give errors

This means that when calling the program from the terminal the workspace would be correct and every inclusion of script would have the folders mapped correctly (from the root).

project/dir/subdir/main_dir/script1.py:

from dir.subdir.other_dir.script2 import *  //also doesn't give errors
like image 37
Traveller Avatar answered Oct 13 '22 21:10

Traveller