How to open any program in Python?

前提是你 提交于 2021-01-27 12:10:43

问题


Well I searched a lot and found different ways to open program in python,

For example:-

import os
os.startfile(path) # I have to give a whole path that is not possible to give a full path for every program/software in my case.

The second one that I'm currently using

import os
os.system(fileName+'.exe')

In second example problem is:-

  1. If I want to open calculator so its .exe file name is calc.exe and this happen for any other programs too (And i dont know about all the .exe file names of every program).
  2. And assume If I wrote every program name hard coded so, what if user installed any new program. (my program wont able to open that program?)

If there is no other way to open programs in python so Is that possible to get the list of all install program in user's computer. and there .exe file names (like:- calculator is calc.exe you got the point).

If you want to take a look at code

Note: I want generic solution.


回答1:


There's always:

from subprocess import call
call(["calc.exe"])

This should allow you to use a dict or list or set to hold your program names and call them at will. This is covered also in this answer by David Cournapeau and chobok.




回答2:


You can try with os.walk :

import os

exe_list=[]

for root, dirs, files in os.walk("."):
 #print (dirs)
 for j in dirs:
  for i in files:
   if i.endswith('.exe'):
     #p=os.getcwd()+'/'+j+'/'+i
     p=root+'/'+j+'/'+i
     #print(p)
     exe_list.append(p)


for i in exe_list :
  print('index : {} file :{}'.format(exe_list.index(i),i.split('/')[-1]))

ip=int(input('Enter index of file :'))

print('executing {}...'.format(exe_list[ip]))
os.system(exe_list[ip])
  1. os.getcwd()+'/'+i prepends the path of file to the exe file starting from root.
  2. exe_list.index(i),i.split('/')[-1] fetches just the filename.exe
  3. exe_list stores the whole path of an exe file at each index



回答3:


Can be done with winapps

First install winapps by typing:

pip install winapps

After that use the library:

# This will give you list of installed applications along with some information

import winapps 

for app in winapps.list_installed(): 
    print(app)

If you want to search for an app you can simple do:

application = 'chrome'

for app in winapps.search_installed(application): 
    print(app)


来源:https://stackoverflow.com/questions/48483765/how-to-open-any-program-in-python

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