0

I have a python script that runs succesfully from within pycharm terminal, setup as a virtual enviroment, but not from the windows terminal. I haven't set any windows enviroment variables.

Python is throwing FileNotFoundError when the script is loading external text files.

I came across this thread: Script running in PyCharm but not from the command line and i think the working directory is not correct when running from the windows terminal.

I do not understand the discrepancy. What does Pycharm different than the windows terminal? and how do i fix it?

cs95
  • 379,657
  • 97
  • 704
  • 746
Decimoseptimo
  • 103
  • 11

1 Answers1

2

By default, PyCharm's current directory refers to the path to your PyCharm sandbox. If you've placed any files there, they'll load without any issues in PyCharm.

From the command line, however, you'll either need to specify a fully qualified path (to where those files actually are), or you'd need to move them to the directory from where you run your script.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • @coldspeed so an option is to use full paths in the source code, i'm worried this could affect OS portability. Other option is to move the files, i guess it would do but i think the files belong where they are (the project root). So, how do I set the current directory as pycharm does, but now for the command line? – Decimoseptimo Aug 26 '17 at 15:57
  • @Decimoseptimo Why not just keep the files in the same directory? Or you could have your program read a config file which contains file paths to your data that has a default value but can be set by users. – cs95 Aug 26 '17 at 15:59
  • @coldspeed python.exe is in \virtual-env\Scripts\, when running from pycharm the working dir correctly is \, when running from CMD.exe the working dir incorrectly is \virtual-env\Scripts\, i want my project files to be in my project root \, if pycharm can set it like that, why can't i? – Decimoseptimo Aug 26 '17 at 17:08
  • @Decimoseptimo As a quick fix you could do `import os; os.chdir('\')` in your script. – cs95 Aug 26 '17 at 17:09
  • @coldspeed I used os.chdir(os.path.dirname(__file__)) to account for other filesystems. Thank you very much sir. – Decimoseptimo Aug 26 '17 at 18:19
  • @coldspeed Could you please explain more details about this and if possible can you create some simple example and steps to do it? Because I'm totally beginner in Python. My issue is python cannot detect any module. Thank you – user2851376 Jul 24 '18 at 04:35