Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script running in PyCharm but not from the command line

Tags:

When I try to run my program from the PyCharm IDE everything works fine but if I type in Fedora:

python myScript.py 

in a shell prompt I get an import error from 1 of the module.

ImportError : No modue named myDependency

What does PyCharm do that allows the interpreter to find my dependencies when launched from the IDE? How can I get my script to find its dependencies so it can be launched with a singe command?

like image 481
Asics Avatar asked Apr 10 '15 04:04

Asics


People also ask

Why is my PyCharm code not running?

Make sure the file that you want to run is on top. Hit ctrl+shift+F10 to run. The run button should be enabled again.

How do I run a Python script in terminal?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

How do I run a current script in PyCharm?

The key combination you are looking for is Ctrl + Shift + F10 . This will run the current script with current being the one displayed in the viewer. Alt+Shift+F10 in PyCharm 2020.3.


2 Answers

There are a few possible things that can be causing this:

  1. The same python interpreter? Check with import sys; print(sys.executable)
  2. Is it the same working directory? Check with import os; print(os.getcwd())
  3. Discrepancies in sys.path, which is the list python searches sequentially for import locations, can possibly caused by environment variables. Check with import sys; print(sys.path).
like image 170
wim Avatar answered Sep 21 '22 12:09

wim


Adding this worked for me:

from os import sys, path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) 
like image 23
Ohad Lahav Avatar answered Sep 19 '22 12:09

Ohad Lahav