Home > OS >  How to show program on the screen if it was opened?
How to show program on the screen if it was opened?

Time:12-17

I have a problem with how to show a program window if it was opened how I open it is using

import os
os.startfile('path/to/progarm.exe')

But if progarm.exe is opened and I forgot to close when I run that script again, A program.exe doesn't show on the screen when I was on another window.

So which script can show up the opened program?

CodePudding user response:

The main reason is that your script lost the focus the opened programs windows. You can control windows with parameters.

os.startfile(path[, operation][, arguments][, cwd][, show_cmd])

also, you can check detail information here. https://docs.python.org/3/library/os.html#os.startfile

CodePudding user response:

To do what you want, you need to provide the path to the program in your machine.

import os
ms_word = r"C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE"
os.startfile(ms_word)

CodePudding user response:

I would not recommend doing what you are doing the way you are doing it. Python has a subprocess module to do things like these, with functions specifically designed to do what you are doing. The easiest way to do what you are trying to do is to use the subprocess.runfunction.

import subprocess
subprocess.run(['path/to/app.exe', 'param1', 'param2'..], shell=True, check=True)
# params are optional.

However, subprocess.run is blocking, i.e., the script will not exit unless you close your launched application.

You can in that case use the subprocess.Popen class. This invokes the process and allows you to communicate with it asynchronously. However, if your objective is only to launch an app and shut down your script, then just call it as you made a call to run. The links I have provided has some examples. there are platform level considerations to make in the case of the parent-child process relationships, e.g. keep child running if the parent dies, kill the child with the parent, keep both of them running independently and allow them to die separately. probably this answer and this answer would provide you with some hints.

However, if you just want to launch an application and nothing else, just use the system shell, no?

  • Related