Issue #22221: Backported fixes from Python 3 (issue #18960).

* Now the source encoding declaration on the second line isn't effective if
  the first line contains anything except a comment.  This affects compile(),
  eval() and exec() too.

* IDLE now ignores the source encoding declaration on the second line if the
  first line contains anything except a comment.

* 2to3 and the findnocoding.py script now ignore the source encoding
  declaration on the second line if the first line contains anything except
  a comment.
diff --git a/Tools/scripts/findnocoding.py b/Tools/scripts/findnocoding.py
index 5d93290..70b1a66 100755
--- a/Tools/scripts/findnocoding.py
+++ b/Tools/scripts/findnocoding.py
@@ -33,6 +33,7 @@
 
 
 decl_re = re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)')
+blank_re = re.compile(r'^[ \t\f]*(?:[#\r\n]|$)')
 
 def get_declaration(line):
     match = decl_re.match(line)
@@ -57,7 +58,8 @@
     line1 = infile.readline()
     line2 = infile.readline()
 
-    if get_declaration(line1) or get_declaration(line2):
+    if (get_declaration(line1) or
+        blank_re.match(line1) and get_declaration(line2)):
         # the file does have an encoding declaration, so trust it
         infile.close()
         return False