How to get the application name having the process name using python? - python

I want to get the name of running application having the process name for e.g. pycharm64.exe-->Pycharm or chrome.exe --> Google chrome
Here's what I have achieved so far
import wmi
c = wmi.WMI()
def get_process_name(hwnd):
"""Get applicatin filename given hwnd."""
try:
_, pid = win32process.GetWindowThreadProcessId(hwnd)
for p in c.query('SELECT Name FROM Win32_Process WHERE ProcessId = %s' % str(pid)):
exe = p.Name
# print(GetFileVersionInfo(exe))
break
return exe
except:
return None
while True :
time.sleep(3)
print(get_process_name(win32gui.GetForegroundWindow()))

Related

get audio device GUID in Python

I am trying to get GUID of audio device. The GUID can be found in registry Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\ the guid should look like {0.0.0.00000000}.{37e73048-025a-47ea-bf9f-59d5ef8f2b43}
basically like this. but I want in python Getting GUID of audio output device (speaker,headphones)
I've tried myself but only thing I can find is to use command line and parse it in Python
import subprocess
sd = subprocess.run(
["pnputil", "/enum-devices", "/connected", "/class", "AudioEndpoint"],
capture_output=True,
text=True,
)
output = sd.stdout.split("\n")[1:-1]
def getDevices(devices):
deviceList = {}
for device in range(len(devices)):
if "Instance ID:" in devices[device]:
deviceList[devices[device+1].split(":")[-1].strip()] = devices[device].split("\\")[-1].strip()
return deviceList
print(getDevices(output))
which got me
{'Headset (Soundcore Life Q30 Hands-Free)': '{0.0.0.00000000}.{4ac89ef7-f00d-4069-b96b-421bd3276295}', 'Speakers (Echo Dot-BQP)': '{0.0.0.00000000}.{8085b216-297a-4d02-bc3d-83b997b79524}', 'Headphones (Soundcore Life Q30)': '{0.0.0.00000000}.{37e73048-025a-47ea-bf9f-59d5ef8f2b43}'}
Hopping there is better way
from __future__ import print_function
import comtypes
from pycaw.pycaw import AudioUtilities, IMMDeviceEnumerator, EDataFlow, DEVICE_STATE
from pycaw.constants import CLSID_MMDeviceEnumerator
def MyGetAudioDevices(direction="in", State = DEVICE_STATE.ACTIVE.value):
devices = []
# for all use EDataFlow.eAll.value
if direction == "in":
Flow = EDataFlow.eCapture.value # 1
else:
Flow = EDataFlow.eRender.value # 0
deviceEnumerator = comtypes.CoCreateInstance(
CLSID_MMDeviceEnumerator,
IMMDeviceEnumerator,
comtypes.CLSCTX_INPROC_SERVER)
if deviceEnumerator is None:
return devices
collection = deviceEnumerator.EnumAudioEndpoints(Flow, State)
if collection is None:
return devices
count = collection.GetCount()
for i in range(count):
dev = collection.Item(i)
if dev is not None:
if not ": None" in str(AudioUtilities.CreateDevice(dev)):
devices.append(AudioUtilities.CreateDevice(dev))
return devices
output_device = MyGetAudioDevices("out")
input_device = MyGetAudioDevices("in")
print(output_device)
print(input_device)
This worked for me

Is there a way to get the full path of the shell:appsfolder on Windows 10?

I'd like to be able to list the files in the shell:appsfolder in a python script but need the full path to do this using os.list. Is there a way to get the full path (or does anyone know it)? Alternatively, is there a different way I can list these files? Can I "cd" to it?
The idea behind the script is to automate the shortcut creation of all the Windows Store apps (identified by the fact they have a "long name" property I think) and extract those shortcuts to a folder where the program Launchy can detect them. I don't like having to manually go through the process of creating the shortcut (and renaming it to remove the " - shortcut) every time I download or remove an app so I thought I'd automate it.
Here's a function that hopefully does what you want in terms of creating shortcuts for the Windows Store apps that are listed in the "Applications" virtual folder (i.e. FOLDERID_AppsFolder). To classify Windows Store apps, it looks for an exclamation point in the Application User Model ID since the AUMID should be of the form "PackageFamily!ApplicationID" (see Automate Launching UWP Apps). For reliability it cross-checks each package family with the user's registered package families.
import os
import ctypes
import pywintypes
import pythoncom
import winerror
try:
import winreg
except ImportError:
# Python 2
import _winreg as winreg
bytes = lambda x: str(buffer(x))
from ctypes import wintypes
from win32com.shell import shell, shellcon
from win32com.propsys import propsys, pscon
# KNOWNFOLDERID
# https://msdn.microsoft.com/en-us/library/dd378457
# win32com defines most of these, except the ones added in Windows 8.
FOLDERID_AppsFolder = pywintypes.IID('{1e87508d-89c2-42f0-8a7e-645a0f50ca58}')
# win32com is missing SHGetKnownFolderIDList, so use ctypes.
_ole32 = ctypes.OleDLL('ole32')
_shell32 = ctypes.OleDLL('shell32')
_REFKNOWNFOLDERID = ctypes.c_char_p
_PPITEMIDLIST = ctypes.POINTER(ctypes.c_void_p)
_ole32.CoTaskMemFree.restype = None
_ole32.CoTaskMemFree.argtypes = (wintypes.LPVOID,)
_shell32.SHGetKnownFolderIDList.argtypes = (
_REFKNOWNFOLDERID, # rfid
wintypes.DWORD, # dwFlags
wintypes.HANDLE, # hToken
_PPITEMIDLIST) # ppidl
def get_known_folder_id_list(folder_id, htoken=None):
if isinstance(folder_id, pywintypes.IIDType):
folder_id = bytes(folder_id)
pidl = ctypes.c_void_p()
try:
_shell32.SHGetKnownFolderIDList(folder_id, 0, htoken,
ctypes.byref(pidl))
return shell.AddressAsPIDL(pidl.value)
except WindowsError as e:
if e.winerror & 0x80070000 == 0x80070000:
# It's a WinAPI error, so re-raise it, letting Python
# raise a specific exception such as FileNotFoundError.
raise ctypes.WinError(e.winerror & 0x0000FFFF)
raise
finally:
if pidl:
_ole32.CoTaskMemFree(pidl)
def enum_known_folder(folder_id, htoken=None):
id_list = get_known_folder_id_list(folder_id, htoken)
folder_shell_item = shell.SHCreateShellItem(None, None, id_list)
items_enum = folder_shell_item.BindToHandler(None,
shell.BHID_EnumItems, shell.IID_IEnumShellItems)
for item in items_enum:
yield item
def list_known_folder(folder_id, htoken=None):
result = []
for item in enum_known_folder(folder_id, htoken):
result.append(item.GetDisplayName(shellcon.SIGDN_NORMALDISPLAY))
result.sort(key=lambda x: x.upper())
return result
def create_shortcut(shell_item, shortcut_path):
id_list = shell.SHGetIDListFromObject(shell_item)
shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None,
pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
shortcut.SetIDList(id_list)
persist = shortcut.QueryInterface(pythoncom.IID_IPersistFile)
persist.Save(shortcut_path, 0)
def get_package_families():
families = set()
subkey = (r'Software\Classes\Local Settings\Software\Microsoft'
r'\Windows\CurrentVersion\AppModel\Repository\Families')
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, subkey) as hkey:
index = 0
while True:
try:
families.add(winreg.EnumKey(hkey, index))
except OSError as e:
if e.winerror != winerror.ERROR_NO_MORE_ITEMS:
raise
break
index += 1
return families
def update_app_shortcuts(target_dir):
package_families = get_package_families()
for item in enum_known_folder(FOLDERID_AppsFolder):
try:
property_store = item.BindToHandler(None,
shell.BHID_PropertyStore, propsys.IID_IPropertyStore)
app_user_model_id = property_store.GetValue(
pscon.PKEY_AppUserModel_ID).ToString()
except pywintypes.error:
continue
# AUID template: Packagefamily!ApplicationID
if '!' not in app_user_model_id:
continue
package_family, app_id = app_user_model_id.rsplit('!', 1)
if package_family not in package_families:
continue
name = item.GetDisplayName(shellcon.SIGDN_NORMALDISPLAY)
shortcut_path = os.path.join(target_dir, '%s.lnk' % name)
create_shortcut(item, shortcut_path)
print('{}: {}'.format(name, app_user_model_id))
example
if __name__ == '__main__':
desktop = shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, 0, 0)
target_dir = os.path.join(desktop, 'Windows Store Apps')
if not os.path.exists(target_dir):
os.mkdir(target_dir)
update_app_shortcuts(target_dir)

Python check for Completed and failed Task Windows scheduler

Does anyone know of a way or a resource I can look at to be able to check the status of all my Windows tasks I have in the task scheduler? I would like to see if that see if the task failed or was successful. I would like to do this in Python.
I have looked a little at using the win32com.client module. I can see what tasks are but can't find what the status of completed job are.
import win32com.client
scheduler = win32com.client.Dispatch("Schedule.Service")
scheduler.Connect()
tasks = scheduler.GetRunningTasks(1)
names = [tasks.Item(i+1).Name for i in range(tasks.Count)]
print names
The following uses the Task Scheduler API to print basic information for all registered tasks, including the last run time and result.
import win32com.client
TASK_ENUM_HIDDEN = 1
TASK_STATE = {0: 'Unknown',
1: 'Disabled',
2: 'Queued',
3: 'Ready',
4: 'Running'}
scheduler = win32com.client.Dispatch('Schedule.Service')
scheduler.Connect()
n = 0
folders = [scheduler.GetFolder('\\')]
while folders:
folder = folders.pop(0)
folders += list(folder.GetFolders(0))
tasks = list(folder.GetTasks(TASK_ENUM_HIDDEN))
n += len(tasks)
for task in tasks:
settings = task.Definition.Settings
print('Path : %s' % task.Path)
print('Hidden : %s' % settings.Hidden)
print('State : %s' % TASK_STATE[task.State])
print('Last Run : %s' % task.LastRunTime)
print('Last Result: %s\n' % task.LastTaskResult)
print('Listed %d tasks.' % n)
This starts with only the root folder in the list. Each pass through the loop pops a folder; pushes all of its subfolders; and lists the tasks in the folder. It continues until the list of folders is empty.
COM Interfaces
ITaskService
ITaskFolder
IRegisteredTask
ITaskDefinition
ITaskSettings
Alternatively, here's a walk_tasks generator that's modeled on the standard library's os.walk.
import os
import pywintypes
import win32com.client
TASK_ENUM_HIDDEN = 1
TASK_STATE = {
0: 'Unknown',
1: 'Disabled',
2: 'Queued',
3: 'Ready',
4: 'Running'
}
def walk_tasks(top, topdown=True, onerror=None, include_hidden=True,
serverName=None, user=None, domain=None, password=None):
scheduler = win32com.client.Dispatch('Schedule.Service')
scheduler.Connect(serverName, user, domain, password)
if isinstance(top, bytes):
if hasattr(os, 'fsdecode'):
top = os.fsdecode(top)
else:
top = top.decode('mbcs')
if u'/' in top:
top = top.replace(u'/', u'\\')
include_hidden = TASK_ENUM_HIDDEN if include_hidden else 0
try:
top = scheduler.GetFolder(top)
except pywintypes.com_error:
if onerror is not None:
onerror(error)
return
for entry in _walk_tasks_internal(top, topdown, onerror, include_hidden):
yield entry
def _walk_tasks_internal(top, topdown, onerror, flags):
try:
folders = list(top.GetFolders(0))
tasks = list(top.GetTasks(flags))
except pywintypes.com_error as error:
if onerror is not None:
onerror(error)
return
if not topdown:
for d in folders:
for entry in _walk_tasks_internal(d, topdown, onerror, flags):
yield entry
yield top, folders, tasks
if topdown:
for d in folders:
for entry in _walk_tasks_internal(d, topdown, onerror, flags):
yield entry
Example
if __name__ == '__main__':
n = 0
for folder, subfolders, tasks in walk_tasks('/'):
n += len(tasks)
for task in tasks:
settings = task.Definition.Settings
print('Path : %s' % task.Path)
print('Hidden : %s' % settings.Hidden)
print('State : %s' % TASK_STATE[task.State])
print('Last Run : %s' % task.LastRunTime)
print('Last Result: %s\n' % task.LastTaskResult)
print('Listed %d tasks.' % n)
task scheduler can be accessed from command line using schtasks and at
schtasks: https://technet.microsoft.com/en-us/library/cc772785%28v=ws.10%29.aspx
at: https://technet.microsoft.com/en-us/library/cc755618%28v=ws.10%29.aspx
run schtasks /query from python using subprocess.check_output see
Running windows shell commands with python
https://technet.microsoft.com/en-us/library/cc722006.aspx
The tasklist command lists all running programs and services or in powershell get-process
https://superuser.com/questions/914782/how-do-you-list-all-processes-on-the-command-line-in-windows

Python multithreading raw_input

I'm currently doing some work with multithreading and i'm trying to figure out why my program isn't working as intended.
def input_watcher():
while True:
input_file = os.path.abspath(raw_input('Input file name: '))
compiler = raw_input('Choose compiler: ')
if os.path.isfile(input_file):
obj = FileObject(input_file, compiler)
with file_lock:
files.append(obj)
print 'Adding %s with %s as compiler' % (obj.file_name, obj.compiler)
else:
print 'File does not exists'
This is running in one thread and it works fine until i start adding adding the second fileobject.
This is the output from the console:
Input file name: C:\Users\Victor\Dropbox\Private\multiFile\main.py
Choose compiler: aImport
Adding main.py with aImport as compiler
Input file name: main.py updated
C:\Users\Victor\Dropbox\Private\multiFile\main.py
Choose compiler: Input file name: Input file name: Input file name: Input file name:
The input filename keeps popping up the second i added the second filename and it ask for a compiler. The program keeps printing input file name until it crashes.'
I have other code running in a different thread, i don't think it has anything to do with the error, but tell me if you think you need to see it and i will post it.
the full code:
import multiprocessing
import threading
import os
import time
file_lock = threading.Lock()
update_interval = 0.1
class FileMethods(object):
def a_import(self):
self.mod_check()
class FileObject(FileMethods):
def __init__(self, full_name, compiler):
self.full_name = os.path.abspath(full_name)
self.file_name = os.path.basename(self.full_name)
self.path_name = os.path.dirname(self.full_name)
name, exstention = os.path.splitext(full_name)
self.concat_name = name + '-concat' + exstention
self.compiler = compiler
self.compiler_methods = {'aImport': self.a_import}
self.last_updated = os.path.getatime(self.full_name)
self.subfiles = []
self.last_subfiles_mod = {}
def exists(self):
return os.path.isfile(self.full_name)
def mod_check(self):
if self.last_updated < os.path.getmtime(self.full_name):
self.last_updated = os.path.getmtime(self.full_name)
print '%s updated' % self.file_name
return True
else:
return False
def sub_mod_check(self):
for s in self.subfiles:
if self.last_subfiles_mod.get(s) < os.path.getmtime(s):
self.last_subfiles_mod[s] = os.path.getmtime(s)
return True
return False
files = []
def input_watcher():
while True:
input_file = os.path.abspath(raw_input('Input file name: '))
compiler = raw_input('Choose compiler: ')
if os.path.isfile(input_file):
obj = FileObject(input_file, compiler)
with file_lock:
files.append(obj)
print 'Adding %s with %s as compiler' % (obj.file_name, obj.compiler)
else:
print 'File does not exists'
def file_manipulation():
if __name__ == '__main__':
for f in files:
p = multiprocessing.Process(target=f.compiler_methods.get(f.compiler)())
p.start()
#f.compiler_methods.get(f.compiler)()
def file_watcher():
while True:
with file_lock:
file_manipulation()
time.sleep(update_interval)
iw = threading.Thread(target=input_watcher)
fw = threading.Thread(target=file_watcher)
iw.start()
fw.start()
This is happening because you're not using an if __name__ == "__main__": guard, while also using multiprocessing.Process on Windows. Windows needs to re-import your module in the child processes it spawns, which means it will keep creating new threads to handle inputs and watch files. This, of course, is a recipe for disaster. Do this to fix the issue:
if __name__ == "__main__":
iw = threading.Thread(target=input_watcher)
fw = threading.Thread(target=file_watcher)
iw.start()
fw.start()
See the "Safe importing of the main module" section in the multiprocessing docs for more info.
I also have a feeling file_watcher isn't really doing what you want it to (it will keep re-spawning processes for files you've already processed), but that's not really related to the original question.

synchronise folders according to datetime

I am very new to python and trying to work on this script which recieves data from multiple ftp sites and download yesterday data according to date directory to my local folder. but if the receives fails on any day it would not update that day records and would go to the next day. I want to sync the files that even if it is missed on particular it should complete sync teh new files to local folder I have tried looking at rsync but need your help to process it on the script.this is my script.
MAX_CHILDREN = 16
ftp_site_prog = "/usr/local/bin/ftp_site.py"
class SpawnQ:
def __init__(self, max_pids):
self.max_pids = max_pids
self.queue = []
tmp = re.split("/", ftp_site_prog)
self.my_name = tmp[-1]
def addQ(self, site_id):
self.queue.append(site_id)
return
def runQ(self):
while (len(self.queue) != 0):
# Check how many sessions are running
cmd = """ps -ef | grep "%s" | grep -v grep""" % self.my_name
num_pids = 0
for line in os.popen(cmd).readlines():
num_pids = num_pids + 1
if (num_pids < self.max_pids):
site_id = self.queue.pop()
# print site_id
# print "Forking........"
fpid = os.fork()
if fpid:
# print "Created child: ", fpid
os.waitpid(fpid, os.WNOHANG)
else:
# print "This is the Child"
# Exec the ftp_site
arg_string = "%s" % site_id
args = [arg_string]
os.execvp(ftp_site_prog, (ftp_site_prog,) + tuple(args))
how to call rsync on my py script.//os.system("rsync -ftp_site_prog, (ftp_site_prog,)+ tuple(args))
sys.exit(0)
else:
# print "Waiting for a spare process...."
time.sleep(10)
return
# Get a list of the sites
db_obj = nprint.celDb()
site_list = db_obj.get_all_site_ids()
myQ = SpawnQ(MAX_CHILDREN)
for site_id in site_list:
myQ.addQ(site_id)
myQ.runQ()
# Wait until we only have the parent left
# Check how many sessions are running
tmp = re.split("/",ftp_site_prog)
ftp_name = tmp[-1]
cmd = """ps -ef | grep "%s" | grep -v grep""" % ftp_name
num_pids = MAX_CHILDREN
while (num_pids > 0):
num_pids = 0
for line in os.popen(cmd).readlines():
num_pids = num_pids + 1
time.sleep(60)
today = datetime.date.today()
daydelta = datetime.timedelta(days=1)
yesterday = today - daydelta
Much of this can be accomplished with the ftplib module for the retrieval of files from standard FTP servers. If you are dealing with SFTP servers you can use the paramiko library.

Categories

Resources