Reputation: 10869
With Python 3.4.2 on Windows I want to open the explorer with the folder of the currently running script like this:
import os, subprocess
subprocess.check_call(['explorer', os.path.dirname(__file__)])
Instead I see that the explorer is opened by with a default folder "C:\Users\XX\Documents" and an error is thrown:
Traceback (most recent call last):
File "C:/XXX/YYY.py", line 9, in <module>
subprocess.check_call(['explorer', os.path.dirname(__file__)])
File "C:\Python34\lib\subprocess.py", line 561, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['explorer', 'C:/XXX']' returned non-zero exit status 1
and although os.path.dirname
returns paths with slashes on Windows (backslashes are path seperators) you can copy and paste it into the explorer and it will open the location just fine. (XXX is the path part, YYY the file name part)
Furthermore, if you manually write the path as it is in the explorer (with backslashes), even then the command fails.
subprocess.check_call(['explorer', r'C:\Users'])
But at least the explorer will open the right directory despite of throwing the same error (so maybe using call
instead of check_call
).
What's going on here? How can I show the folder of the running Python script file in the explorer?
Upvotes: 2
Views: 699
Reputation: 97631
You need to use backslashes in your paths for windows explorer to undestand them. Testing from the command line, this works:
> explorer C:\Users
But this doesn't
> explorer C:/Users
Use os.path.normpath
to convert the forward slashes into back slashes
Note that abspath
, according to the docs, is implemented as normpath(join(os.getcwd(), path))
, so the other solution also addresses this issue.
Upvotes: 3
Reputation: 8547
You need to send the absolute path to the directory by calling os.path.abspath
, and switch check_call
with call
(as you suspected).
import os
import subprocess
dirname = (os.path.dirname(os.path.abspath(__file__)))
subprocess.call(['explorer', dirname])
subprocess.check_call
raises an exception if the return code of the process is nonzero. Even when explorer doesn't actually have an error, it has a non-zero return status, so you get an exception.
That's actually unrelated to the problem, though. The problem is that you were passing a string with forward slashes to explorer. This would have happened if you called your script like python path/to/script.py
instead of python path\to\script.py
. If you pass the absolute path to subprocess.call, explorer will open in the right directory. You would get the same error if you passed an empty string as the second arg to subprocess.call.
Upvotes: 3