0

First of all, I am new to programming. To run python code in an external shell window, I followed the instructions given on this page link

My problem is that if I save the python file in any path that contains a folder name with a space, it gives me this error:

C:\Python34\python.exe: can't open file 'C:\Program': [Errno 2] No such file or directory

Does not work:

C:\Program Files\Python Code

Works:

C:\ProgramFiles\PythonCode

could someone help me fix the problem???

Here is the code:

    import sublime
import sublime_plugin
import subprocess
class PythonRunCommand(sublime_plugin.WindowCommand):
    def run(self):
        command = 'cmd /k "C:\Python34\python.exe" %s' % sublime.active_window().active_view().file_name()
        subprocess.Popen(command)
1
  • Try adding quotes in your command = 'cmd ... "%s"' Commented Mar 31, 2017 at 8:26

1 Answer 1

2

subprocess methods accept a string or a list. Passing as a string is the lazy way: just copy/paste your command line and it works. That is for hardcoded commands, but things get complicated when you introduce parameters known at run-time only, which may contain spaces, etc...

Passing a list is better because you don't need to compose your command and escape spaces by yourself. Pass the parameters as a list so it's done automatically and better that you could do:

command = ['cmd','/k',r"C:\Python34\python.exe",sublime.active_window().active_view().file_name()]

And always use raw strings (r prefix) when passing literal windows paths or you may have some surprises with escape sequences meaning something (linefeed, tab, unicode...)

In this particular case, if file associations are properly set, you only need to pass the python script without any other command prefix:

command = [sublime.active_window().active_view().file_name()]

(you'll need shell=True added to the subprocess command but it's worth it because it avoids to hardcode python path, and makes your plugin portable)

Sign up to request clarification or add additional context in comments.

3 Comments

are you sure it will work with folders that have names with space?
see my edit (first sentence). subprocess accepts both.
Thanks a lot, you are great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.