0

I'm starting a project that is broken up into multiple packages and files. The problem I quickly encountered is that imports that work when run internally from PyCharm fail when run from a command line. Heres my Current Directory

Current Directory

The contents of File C:

print("File C imported")

The contents of File B:

print("File B imported")


class ClassB:
    def __init__(self):
        print("Class B made")

The contents of File A:

import src.packageB.fileB as B
import packageC.fileC

B.ClassB()

print("packageA ran")

When I push the play button in PyCharm, all the different modules import and it prints:

File B imported
File C imported
Class B made
packageA ran

When fileA is ran from a command line, the error is thrown saying "No module name src". I've tried running fileA.py from "PackageTest", "src", and "packageA", but changing the directory from where python runs doesn't seem to make a difference.

I'm sure I don't understand the fundamental problem of why this is occurring. I'd really like to understand so when this project becomes much more complex and deep, I can solve import problems just like this. I appreciate the help!

sophros
  • 14,672
  • 11
  • 46
  • 75
Lacrosse343
  • 491
  • 1
  • 3
  • 18
  • 2
    This question is a little broad. Is it "how does python packaging work in general", or "how does pycharm find source files for import suggestions", or both? – Arne Oct 01 '19 at 07:43
  • Does this answer your question? [ImportError in the console, but import is working in PyCharm](https://stackoverflow.com/questions/36002884/importerror-in-the-console-but-import-is-working-in-pycharm) – sophros Feb 26 '20 at 13:02
  • Don't make `src` a package if it logically isn't one. If you have some packages or modules in a subdirectory like `src/` you just need to make the proper arrangements to ensure that that directory is on your python path (eg. `sys.path`) when you try to import `packageA` or `packageB`. Study up on how Python imports work and how paths are searched. – Iguananaut Feb 26 '20 at 13:07

1 Answers1

0

The issue you are encountering relates to the way you run scripts in PyCharm - for each of the run configurations you specify the working directory.

The behaviour should be the same as long as you cd to the same working directory when running a script from the command line.

If you are unsure about which one is it you can check in the configuration or the console output.

It may also worth reading answers to this question: Import statement works on PyCharm but not from terminal

sophros
  • 14,672
  • 11
  • 46
  • 75