Skip to content

Commit ff44289

Browse files
scopmyint
authored andcommitted
Shebang detection improvements (#438)
* Recognize python with arguments in shebang * Recognize python with d/m/u suffix in shebang https://www.python.org/dev/peps/pep-3149/#proposal * Recognize python with minor version in shebang * Avoid unnecessary line splitting in shebang search * Add test for python shebang-like not on the first line
1 parent eeb6263 commit ff44289

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

pyflakes/api.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
__all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main']
1616

17-
PYTHON_SHEBANG_REGEX = re.compile(br'^#!.*\bpython[23w]?\b\s*$')
17+
PYTHON_SHEBANG_REGEX = re.compile(br'^#!.*\bpython([23](\.\d+)?|w)?[dmu]?\s')
1818

1919

2020
def check(codeString, filename, reporter=None):
@@ -118,8 +118,7 @@ def isPythonFile(filename):
118118
except IOError:
119119
return False
120120

121-
first_line = text.splitlines()[0]
122-
return PYTHON_SHEBANG_REGEX.match(first_line)
121+
return PYTHON_SHEBANG_REGEX.match(text)
123122

124123

125124
def iterSourceCode(paths):

pyflakes/test/test_api.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,9 +214,35 @@ def test_shebang(self):
214214
with open(pythonw, 'w') as fd:
215215
fd.write('#!/usr/bin/env pythonw\n')
216216

217+
python3args = os.path.join(self.tempdir, 'g')
218+
with open(python3args, 'w') as fd:
219+
fd.write('#!/usr/bin/python3 -u\n')
220+
221+
python2u = os.path.join(self.tempdir, 'h')
222+
with open(python2u, 'w') as fd:
223+
fd.write('#!/usr/bin/python2u\n')
224+
225+
python3d = os.path.join(self.tempdir, 'i')
226+
with open(python3d, 'w') as fd:
227+
fd.write('#!/usr/local/bin/python3d\n')
228+
229+
python38m = os.path.join(self.tempdir, 'j')
230+
with open(python38m, 'w') as fd:
231+
fd.write('#! /usr/bin/env python3.8m\n')
232+
233+
python27 = os.path.join(self.tempdir, 'k')
234+
with open(python27, 'w') as fd:
235+
fd.write('#!/usr/bin/python2.7 \n')
236+
237+
# Should NOT be treated as Python source
238+
notfirst = os.path.join(self.tempdir, 'l')
239+
with open(notfirst, 'w') as fd:
240+
fd.write('#!/bin/sh\n#!/usr/bin/python\n')
241+
217242
self.assertEqual(
218243
sorted(iterSourceCode([self.tempdir])),
219-
sorted([python, python2, python3, pythonw]))
244+
sorted([python, python2, python3, pythonw, python3args, python2u,
245+
python3d, python38m, python27]))
220246

221247
def test_multipleDirectories(self):
222248
"""

0 commit comments

Comments
 (0)