Python works in PyCharm but not from terminal

后端 未结 7 764
你的背包
你的背包 2020-12-31 03:06

I recently figured out how to import modules for unittesting in python. As a solution to this, I use:

sys.path.append(os.path.abspath(os.path.join(os.path.di         


        
相关标签:
7条回答
  • 2020-12-31 03:42

    When running a script from within PyCharm, it runs it in an environment with PYTHONPATH set to the list of all the folders that are marked "Sources Root" (with a blue folder icon) in the project explorer.

    Outside of PyCharm, PYTHONPATH is not normally set. The first entry in sys.path refers to the current working directory where the script was run from. As long as you run your script with your terminal's working directory as the folder containing Dev, it should be able to find the Dev.test module, regardless of the extra entry added to sys.path.

    Once you get the working directory correct, you should be able to remove the sys.path hack.

    0 讨论(0)
  • 2020-12-31 03:45

    I too have had this issue - and the PYTHONPATH setting set by PyCharm did seem to be the issue.

    My alternative (as I was nearly finished writing the code) was to generate a setup.py - and install the classes/structure in my local virtual python environment.

    Hope this helps..

    0 讨论(0)
  • 2020-12-31 03:45

    I would recommend trying out $ pip install . in your source directory. This will install your own packages for your project.

    0 讨论(0)
  • 2020-12-31 03:50

    I had similar problem. I think the problem is that Pycharm modifies PYTHONPATH so before running your script:

    1. cd to the file where python file resides
    2. run export PYTHONPATH=.
    3. run the script

    You can also create "main" python file where you set the python path and then call the other modules

    0 讨论(0)
  • 2020-12-31 03:53
    sys.path.append(os.getcwd()[:os.getcwd().index('Dev')])
    

    I added this to my imports and it seems to have solved the problem. However, this doesn't seem like it would be the right way to do it; it will do for now.

    0 讨论(0)
  • 2020-12-31 03:53

    What @codewarrior has said about the PyCharm setting its own PYTHONPATH is correct. But sys.path didn't have my current working directory. So to get around this problem, I updated my PYTHONPATH (or you can edit sys.path).

    Setting PYTHONPATH

    export PYTHONPATH=$PYTHONPATH:`pwd`  (OR your project root directory)
    

    Updating sys.path

    import sys
    sys.path.insert(0,'<project directory>') OR
    sys.path.append('<project directory>')
    

    You can use insert/append based on the order in which you want your project to be searched.

    HTH.

    0 讨论(0)
提交回复
热议问题