Simeon Borko
Simeon Borko

Reputation: 100

Run python script in package

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:

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:

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'

Upvotes: 0

Views: 1137

Answers (2)

Simeon Borko
Simeon Borko

Reputation: 100

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

Upvotes: 0

Steve
Steve

Reputation: 989

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.

Upvotes: 1

Related Questions