windows双击运行python脚本_从命令提示符或Windows上的“双击”检测脚本启动

下面是一个如何获取当前正在运行的脚本的父进程id和名称的示例。正如Tomalak建议的那样,这可以用来检测脚本是从命令提示符还是通过在资源管理器中双击启动的。在import win32pdh

import os

def getPIDInfo():

"""

Return a dictionary with keys the PID of all running processes.

The values are dictionaries with the following key-value pairs:

- name:

- parent_id:

"""

# get the names and occurences of all running process names

items, instances = win32pdh.EnumObjectItems(None, None, 'Process', win32pdh.PERF_DETAIL_WIZARD)

instance_dict = {}

for instance in instances:

instance_dict[instance] = instance_dict.get(instance, 0) + 1

# define the info to obtain

counter_items = ['ID Process', 'Creating Process ID']

# output dict

pid_dict = {}

# loop over each program (multiple instances might be running)

for instance, max_instances in instance_dict.items():

for inum in xrange(max_instances):

# define the counters for the query

hq = win32pdh.OpenQuery()

hcs = {}

for item in counter_items:

path = win32pdh.MakeCounterPath((None,'Process',instance, None,inum,item))

hcs[item] = win32pdh.AddCounter(hq,path)

win32pdh.CollectQueryData(hq)

# store the values in a temporary dict

hc_dict = {}

for item, hc in hcs.items():

type,val=win32pdh.GetFormattedCounterValue(hc,win32pdh.PDH_FMT_LONG)

hc_dict[item] = val

win32pdh.RemoveCounter(hc)

win32pdh.CloseQuery(hq)

# obtain the pid and ppid of the current instance

# and store it in the output dict

pid, ppid = (hc_dict[item] for item in counter_items)

pid_dict[pid] = {'name': instance, 'parent_id': ppid}

return pid_dict

def getParentInfo(pid):

"""

Returns a PID, Name tuple of the parent process for the argument pid process.

"""

pid_info = getPIDInfo()

ppid = pid_info[pid]['parent_id']

return ppid, pid_info[ppid]['name']

if __name__ == "__main__":

"""

Print the current PID and information of the parent process.

"""

pid = os.getpid()

ppid, ppname = getParentInfo(pid)

print "This PID: %s. Parent PID: %s, Parent process name: %s" % (pid, ppid, ppname)

dummy = raw_input()

从命令提示符运行时,此输出:This PID: 148. Parent PID: 4660, Parent process name: cmd

在资源管理器中双击启动时,此输出:This PID: 1896. Parent PID: 3788, Parent process name: explorer

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值