检测脚本从命令提示符启动或在Windows上"双击"

pki*_*kit 7 python windows

是否可以检测Python脚本是从命令提示符启动还是用户"双击"Windows上的文件浏览器中的.py文件?

小智 8

如果从命令行运行,则会定义一个额外的环境变量"PROMPT".

如果从资源管理器中单击此脚本将暂停,如果从命令行运行,则不会暂停:

import os

print 'Hello, world!'

if not 'PROMPT' in os.environ:
    raw_input()
Run Code Online (Sandbox Code Playgroud)

使用Python 2.7在Windows 7上测试


pki*_*kit 5

下面举例说明如何获取当前运行脚本的父进程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: <Name of the process PID>
        - parent_id: <PID of this process parent>
    """

    # 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()
Run Code Online (Sandbox Code Playgroud)

从命令提示符运行时,输出:

此PID:148。父PID:4660,父进程名称:cmd

通过双击资源管理器启动时,输出:

本PID:1896。父PID:3788,父进程名称:explorer