1

I want to make my python program to execute a file in Windows. That means that if I try to execute a .txt file, it would open with the default .txt viewer. Is that possible?

I tried subprocess.call, but I get WindowsError: [Error 193] %1 is not a valid Win32 application. The file I'm trying to run is a .png file.

linusg
  • 6,289
  • 4
  • 28
  • 78
  • Can you post more about what you passed to `subprocess.call`, and the full traceback? The answer is probably in there! – mprat Apr 21 '16 at 19:51
  • @mprat `subprocess.call(["C:\\Path\\To\\png_file.png"])` hoping that it would execute with the default png viewer –  Apr 21 '16 at 19:52
  • you need to use `subprocess.call("file.png", shell=True)` or `os.system("file.png")` instead – ej_f Apr 21 '16 at 19:57

3 Answers3

3
os.startfile("myText.txt") #open text editor
os.startfile("myText.pdf") #open in pdf viewer
os.startfile("myText.html") #open in webbrowser

is how you should do this

however

os.startfile("my_prog.py")

is probably a bad idea because there is no way to know if python is set as the default to open *.py or if a texteditor or ide is set as the default to open *.py

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • Thanks, this is what i was looking for. No cmd window, just simply starting the file –  Apr 21 '16 at 19:59
2

This will start the file with the registered application for .txt extensions:

import os
os.system("start myText.txt")

with subprocess you'll need

subprocess.call("start myText.txt", shell=True)

since start is part of the shell.

thebjorn
  • 26,297
  • 11
  • 96
  • 138
1

Say you have a file myText.txt.
If you want to open that file through the command line, you would simple write ~$ myText.txt.
So in Python, you can just run a cmd command that opens a file. Say:

import os
os.system("myText.txt") #Requires myText.txt and the python file to be in same folder. Otherwise full path is required.

This would open the file in the default editor, or if it's an exe file, just run it.

Yotam Salmon
  • 2,400
  • 22
  • 36
  • The cmd windows was open for quite some time (around 5 seconds), but it did the job. Thanks! –  Apr 21 '16 at 19:55
  • Even when you double click a file, it takes a few seconds to open the file (unless you have an amazing CPU or SSD)... – Yotam Salmon Apr 21 '16 at 19:56