Python subprocess module equivalent for double-click in Windows

血红的双手。 提交于 2019-12-11 11:15:08

问题


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.


回答1:


os.startfile(r'C:\myfile.csv')

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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/4435332/python-subprocess-module-equivalent-for-double-click-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!