Python subprocess module equivalent for double-click in Windows
Asked Answered
C

3

5

I want to open a file using the subprocess module as though the file was double-clicked in Explorer. How do I do that?

I tried the following line:

subprocess.call("C:/myfile.csv", shell=True)

which throws an error saying:

The syntax of the command is incorrect.
'C:\' is not recognized as an internal or external command, operable program or batch file.

How do I emulate a double-click using subprocess? Basically I want to open a CSV file in Excel 2007.

Condor answered 14/12, 2010 at 2:21 Comment(3)
I think subprocess.call(r'C:\myfile.csv', shell=True) should do it (not sure, and os.startfile is cleaner).Mcabee
@Chris: I actually used shell=True, forgot to include it in the question. Using shell=True would produce the error I mentioned above.Condor
I think you missed the fact that Chris used a raw string with a backslash for his path and you didn't in yours (and the difference may be significant).Electroshock
T
10
os.startfile(r'C:\myfile.csv')

(Win32 only. For Mac, run a process with 'open filename'; on Linux/freedesktop-in-general, 'xdg-open filename'.)

Towards answered 14/12, 2010 at 2:30 Comment(1)
+1. subprocess.call tries to run something as an executable. Your CSV file isn't an executable; it's data for one. Each platform has its own utility application for "figure out what kind of file this is and feed it to the appropriate application", which is what you're really trying to do.Swarthy
J
1

I think part of your problem is you're using a unix style slash / as a path separator, instead of the windows backslash . It looks like windows is interpreting /myfile.csv as an argument for the program C:, which is why you're getting that message.

However if you corrected that, I think you'd just get it saying that C:\myfile.csv isn't a program.

Jeepers answered 14/12, 2010 at 3:30 Comment(0)
D
0

I know that this is a bit late, but to do that in python 2.x (not sure about 3) you should use the subprocess module, referencing Popen. Here is the code:

import subprocess
subprocess.Popen(r'explorer /select, "C:\"')

It basically opens the file, and then opens it in the default program.

Dextroamphetamine answered 15/2, 2013 at 2:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.