0

I am struggling with running python script in shell. I use PyCharm where is everything ok, but I want to run script without running PyCharm.

So my project folder is like:

  • data/
    • file.txt
  • main/
    • __init__.py
    • script.py
  • tools/
    • __init__.py
    • my_strings.py

I want to run main/script.py, which start with from tools import my_strings and working directory should be data/.

My PyCharm config is:

  • Script path: <PROJECT>/main/script.py
  • Working directory: <PROJECT>/data
  • Add content roots to PYTHONPATH: YES
  • Add source roots to PYTHONPATH: YES

So I want to run main/script.py in shell on Ubuntu. I tried:

PYTHONPATH=<PROJECT>
cd <PROJECT>/data
python3 ../main/script.py

But I just got: ImportError: No module named 'tools'

Simeon Borko
  • 100
  • 6

2 Answers2

1

Check out this post, it's explains the PYTHONPATH variable.

How to use PYTHONPATH and the documentation the answer points to https://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH

When you run from the data directory by default python can't find your tools directory.

Also regarding your comment about needing to run from the data directory, you could just use open('../data/file.txt') if you decided to run from the main directory instead.

Ideally, you should be able to run your script from anywhere though. I find this snippet very useful os.path.dirname(sys.argv[0]). It returns the directory in which the script exists.

Steve
  • 939
  • 1
  • 6
  • 20
0

I simply forgot to export $PYTHONPATH as suggested by Steve.

Simeon Borko
  • 100
  • 6