Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Programmatically detect whether a file is a Python script

Tags:

python

I'd like to create a git pre-commit hook for my project that runs autopep8 on files modified by the potential commit. I only want to run it on Python files, not the other C++ files, text files, etc. How can I programmatically detect whether a file is a Python file? Not all of the Python files in the repository have the .py extension, so I cannot rely upon that.

like image 556
firebush Avatar asked Jul 30 '20 23:07

firebush


People also ask

How do you check if a file is being written Python?

Simply open the file in Python and move the read/write pointer to the end of the file using the seek() method, then retrieve its position using the tell() method, this position is equal to the size of the file in bytes.

What is Python __ name __?

In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.


1 Answers

You can't.

At least not in such general case and with perfect accuracy. Your best bet is to make sure all your python files in the repo do have .py extension or are disntinguished from other files in some simple, finite amount ways.

Your next best bet is file command.

like image 176
Jan Matějka Avatar answered Nov 15 '22 06:11

Jan Matějka