can you assign a pid to a process via python

Solutions on MaxInterview for can you assign a pid to a process via python by the best coders in the world

showing results for - "can you assign a pid to a process via python"
Paola
04 Feb 2020
1def main():
2    # Fetch information for current processes:
3    proc_info_old = get_proc_info()
4
5    # Extract list of PIDs:
6    pids_old = get_all(proc_info_old, "ProcessId")
7
8
9
10    # Do something that starts one or more new processes:
11    os.system('start notepad.exe')
12
13
14
15    # Fetch information for current processes:
16    proc_info_new = get_proc_info()
17
18    # Extract list of PIDs:
19    pids_new = get_pids(proc_info_new, "ProcessId")
20
21
22
23    # Determine PIDs which are only in pids_new, not in pids_old:
24    new_pids = list(set(pids_new) - set(pids_old))
25
26    # Output new PIDs and the associated command line:
27    for pid in new_pids:
28        cmd = get_for(proc_info_new, "ProcessId", pid, "CommandLine")
29        test.log("PID: %s" % pid)
30        test.log("CMD: %s" % cmd)
31        test.log("")
32
33    os.system("taskkill /f /im notepad.exe")
34
35def get_all(proc_info, get_name):
36    res = []
37    for pi in proc_info:
38        res.append(pi[get_name])
39    return res
40
41def get_for(proc_info, look_for_name, look_for_value, get_name):
42    for pi in proc_info:
43        if pi[look_for_name] == look_for_value:
44            return pi[get_name]
45    return None
46
47def get_proc_info(search_expression=None):
48    if search_expression is None:
49        search_expression = ""
50    else:        
51        search_expression = " WHERE " + search_expression
52
53    # Execute with wmic and capture output:
54    s = 'pushd "' + os.getcwd() + '" && wmic PROCESS ' + search_expression + ' GET * /format:csv <nul'
55    d = subprocess.Popen(s, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0];
56
57    # Strip first empty line produced by wmic:
58    d = d[3:]
59
60    # Write to file (to later read via testData API):
61    fn = "temp.csv"
62    f = codecs.open(fn, "w", "utf8")
63    f.write(d)
64    f.close()
65
66    # Read via testData API:
67    dataset = testData.dataset(fn)
68    all_proc_info = []
69    for row in dataset:
70        proc_info = {}
71        field_names = testData.fieldNames(row)
72        for n in field_names:
73            v = testData.field(row, n)
74            proc_info[n] = v
75        all_proc_info.append(proc_info)
76    os.remove(fn)
77    return all_proc_info