Whenever I open a script (Python or R), I want Sublime automatically changes the current working directory to the path of that file. Is it possible?
I added the setting "working_dir": "$file_path",
to Sublime preferences but it doesn't help.
Whenever I open a script (Python or R), I want Sublime automatically changes the current working directory to the path of that file. Is it possible?
I added the setting "working_dir": "$file_path",
to Sublime preferences but it doesn't help.
Ok, I solved the problem. Here is what I did:
PackageResourceViewer
PackageResourceViewer: Open Resource
Python
resource then open Python.sublime-build
"shell_cmd": "python -u \"$file\"",
Add the following 2 lines:
"cmd": ["python", "-u", "$file"],
"working_dir": "$file_path",
Alternately, you can replace the above 2 lines by:
"shell_cmd": "cd $file_path; python -u \"$file\""
Do the same thing for R
or other build resources if you want Sublime Text 3 automatically change the current working directory in accordance with the active scripts' path.
You can open the python console using the Show Console command in View menu, and then type
import os
os.chdir('/my/directory')
It changes the working directory for the Sublime Text process and whatever process it spawns.
Another solution: You know the console opens with Alt+". When I use the combination Alt+1 it's directly chosing the current file path. And this way is something you have to do every single time you open sublime text.
I was having the same issue, plus if i wanted to import a module, it would always return module not found.
To fix this: I change the first line of my python.sublime-build file to what i have below
{
"shell_cmd": "cd $file_path; python -u \"$file\"",
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
{
"env": "PYTHONIOENCODING": "utf-8",
],
"variants":
}
{
"name": "Syntax Check",
"shell_cmd": "python -m py_compile \"${file}\"",
}
]
}
Being cuper curious, i wanted to know why this was happening, so after doing more investigations about my os, ran:
import os
for k, v in os.environ.items():
print(k, v)
print(os.getcwd())
which returns a dictionary of my environment variables and their values, including 2 that answered my questions in the build results PWD
and OLDPWD
:
PWD /Users/<myname>/code
OLDPWD /Users/<myname>/code/code_py
...
[Finished 0.0ms]
...
[shell_cmd: cd /Users/<myname>/code/code_py; python -u "/Users/<myname>/code/code_py/YT-tutorials.py"]
...
AHA!
because i previously added cd $HOME/code
my ~/.bash_profile, so every time i would build (command+B) in sublime with python, my shell profile would change directories behind the scenes and move me into my ~/code directory.
Now, after changing the python.sublime-build file as mentioned above changed this build behavior has been fixed -- & i hope this helps you too!