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'

7
  • How is your import statement look like in script.py? Commented Mar 20, 2018 at 16:13
  • 1
    Try running it from the top level project folder. Commented Mar 20, 2018 at 16:16
  • @Rafael I wrote it in question: from tools import my_strings Commented Mar 20, 2018 at 16:20
  • You need to set the python path yourself since pycharm isn't doing it for you Commented Mar 20, 2018 at 16:22
  • 1
    did you export it? Commented Mar 20, 2018 at 16:27

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.