Home Download Buy Blog Forum Support

Python scripts running in the wrong folder?

Python scripts running in the wrong folder?

Postby jesse.robertson on Sat Apr 30, 2011 7:11 am

Not sure whether this is meant to be a feature or not, but I have a bunch of matplotlib scripts which output some graphs as pdf files. I have them set up to just save to the current folder, i.e. something like
Code: Select all
figure.savefig('figure.pdf')


When I run the scripts from the command line the files appear in the same folder as the script, but when I run them from within ST (using cmd-B) they appear in the root directory of the ST project. Is this intended? Or does the python sublime build script need to have the current folder specified? It just seems a bit unintuitive at present.
jesse.robertson
 
Posts: 11
Joined: Fri Apr 29, 2011 2:56 am

Re: Python scripts running in the wrong folder?

Postby ratnushock on Sun May 01, 2011 10:12 pm

Hi there!

I have just send a tweet to john about this.
It happens to me on Windows all the time, the files go to C:\Windows\System32.
I don't now where are they going in OSX, but you can figure it out by using os.getcwd()

You can add a few lines on top of your scripts to fix this:

Code: Select all
# Need to import os machinery
import os
# You can also do:
# from os import chdir
# from os.path import dirname

# Get path of current file
cwd = os.path.dirname(__file__)
# Change current working directory to that one
os.chdir(cwd)


It's a bit annoying but.. no other way right now.

Hope it helps!
ratnushock
 
Posts: 8
Joined: Sun May 01, 2011 10:08 pm

Re: Python scripts running in the wrong folder?

Postby jesse.robertson on Mon May 02, 2011 1:59 am

Hi ratnushock, the easiest way I've found to fix this is to go to the Python build script (should be under Python in wherever the packages for ST are stored), and make sure it says:

Code: Select all
{
   "cmd": ["python", "-u", "$file"],
   "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
   "working_dir": "$file_path",
   "selector": "source.python"
}


i.e. add the "working_dir" property.

I guess I'm not sure why this isn't the standard behavior.
jesse.robertson
 
Posts: 11
Joined: Fri Apr 29, 2011 2:56 am

Re: Python scripts running in the wrong folder?

Postby ratnushock on Mon May 02, 2011 11:02 am

Kudos to you jesse!

Your solution is so simple and great that now I'm feeling stupid for not seeing it before :/

Many thanks!
ratnushock
 
Posts: 8
Joined: Sun May 01, 2011 10:08 pm


Return to Technical Support

Who is online

Users browsing this forum: No registered users and 26 guests