![](/img/trans.png)
[英]How can a python script detect whether headphones/earphones are connected to the pc or not?
[英]How to Programmatically detect whether a file is a Python script
我想为我的项目创建一个 git 预提交挂钩,该挂钩在潜在提交修改的文件上运行 autopep8。 我只想在 Python 文件上运行它,而不是其他 C++ 文件、文本文件等。如何以编程方式检测文件是否为 Python 文件? 并非存储库中的所有 Python 文件都具有 .py 扩展名,因此我不能依赖它。
你不能。
至少不是在这种一般情况下并且具有完美的准确性。 最好的办法是确保 repo 中的所有 python 文件都具有 .py 扩展名,或者以一些简单、有限的方式与其他文件区分开来。
您的下一个最佳选择是file
命令。
我很惊讶没有看到一个可靠的答案。 我倾向于:
我知道这遗漏了诸如对解释器进行硬编码的脚本之类的东西,例如:
#! /some/virtual/env/bin/python3
我很想检查#!
后面跟着单词python
的任何地方。
如果你想做同样的事情,第一次切割(带有一些调试打印语句)看起来像:
import os
import re
def is_readable_py_file(filename: str) -> bool:
"""Determine if filename is a python file and return bool."""
if not os.path.isfile(filename):
return False
if os.path.splitext(filename)[1] == ".py":
return True
# Allow #!-specified files without ".py" extension
try:
with open(filename) as infile:
first_line = infile.readline()
if re.match(r"\s*#!\s*/usr/bin/env\s\s*python", first_line):
return True
except Exception as exc:
print(f"Caught exception: {exc}")
print(f"Assuming not a Python file: '{filename}'")
return False
我希望没有一种方法适合每个人,我认为这很粗糙,但如果您只是想复制/粘贴开始,那就试试吧!
哦,我正在考虑的替代检查是(它匹配/usr/bin/env
匹配的所有内容,因此您可以替换它):
if re.match(r"\s*#!.*python", first_line): # python anywhere in shebang
return True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.