python判断文件是否打开_如何用Python判断文件在Windows上是否可执行?

我正在编写^{}实用程序,它在%PATH%中查找与模式匹配的可执行文件。

我需要定义路径中给定的文件名是否可执行(重点是命令行脚本)。在

{基于}我得到:import os

from pywintypes import error

from win32api import FindExecutable, GetLongPathName

def is_executable_win(path):

try:

_, executable = FindExecutable(path)

ext = lambda p: os.path.splitext(p)[1].lower()

if (ext(path) == ext(executable) # reject *.cmd~, *.bat~ cases

and samefile(GetLongPathName(executable), path)):

return True

# path is a document with assoc. check whether it has extension

# from %PATHEXT%

pathexts = os.environ.get('PATHEXT', '').split(os.pathsep)

return any(ext(path) == e.lower() for e in pathexts)

except error:

return None # not an exe or a document with assoc.

其中samefile是:

^{pr2}$

在给定的上下文中,is_executable_win如何改进?Win32 API中的哪些函数可以帮助您?在

p.S时间表现并不重要

subst不考虑驱动器和UNC、unicode路径

如果使用WindowsXP上的函数,LI> C++答案是可以的

示例notepad.exe是可执行的(通常)

如果which.py与某个可执行文件关联(例如。,python.exe)并且.PY在%PATHEXT%中,即,'C:\> which'可以开始:some\path\python.exe another\path\in\PATH\which.py

somefile.doc最有可能是而不是可执行的(例如,当它与Word关联时)

another_file.txt是不是可执行的(通常)

ack.pl是可执行的,如果它与某个可执行文件关联(很可能是perl.exe文件)并且.PL在%PATHEXT%中(也就是说,如果它在路径中,我可以运行ack而不指定扩展名)

在这个问题中什么是“可执行的”def is_executable_win_destructive(path):

#NOTE: it assumes `path` <-> `barename` for the sake of example

barename = os.path.splitext(os.path.basename(path))[0]

p = Popen(barename, stdout=PIPE, stderr=PIPE, shell=True)

stdout, stderr = p.communicate()

return p.poll() != 1 or stdout != '' or stderr != error_message(barename)

其中error_message()依赖于语言。英文版为:def error_message(barename):

return "'%(barename)s' is not recognized as an internal" \

" or external\r\ncommand, operable program or batch file.\r\n" \

% dict(barename=barename)

Ifis_executable_win_destructive()在定义路径是否指向可执行文件时返回。在

示例:>>> path = r"c:\docs\somefile.doc"

>>> barename = "somefile"

然后执行%COMSPEC%(命令行.exe默认情况下):c:\cwd> cmd.exe /c somefile

如果输出如下所示:'somefile' is not recognized as an internal or external

command, operable program or batch file.

那么path不是可执行文件,否则它是可执行的(为了示例起见,假设path和{}之间存在一对一的对应关系)。在

另一个例子:>>> path = r'c:\bin\grepath.py'

>>> barename = 'grepath'

如果.PY在%PATHEXT%中,c:\bin在{}中,则:c:\docs> grepath

Usage:

grepath.py [options] PATTERN

grepath.py [options] -e PATTERN

grepath.py: error: incorrect number of arguments

上述输出不等于error_message(barename),因此'c:\bin\grepath.py'是“可执行的”。在

所以问题是如何找出path是否会在不实际运行的情况下产生错误?什么Win32 API函数以及用于触发“未被识别为内部..”错误的条件是什么?在

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值