test_windows_wrappers.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. """
  2. Python Script Wrapper for Windows
  3. =================================
  4. setuptools includes wrappers for Python scripts that allows them to be
  5. executed like regular windows programs. There are 2 wrappers, one
  6. for command-line programs, cli.exe, and one for graphical programs,
  7. gui.exe. These programs are almost identical, function pretty much
  8. the same way, and are generated from the same source file. The
  9. wrapper programs are used by copying them to the directory containing
  10. the script they are to wrap and with the same name as the script they
  11. are to wrap.
  12. """
  13. import pathlib
  14. import platform
  15. import subprocess
  16. import sys
  17. import textwrap
  18. import pytest
  19. from setuptools._importlib import resources
  20. pytestmark = pytest.mark.skipif(sys.platform != 'win32', reason="Windows only")
  21. class WrapperTester:
  22. @classmethod
  23. def prep_script(cls, template):
  24. python_exe = subprocess.list2cmdline([sys.executable])
  25. return template % locals()
  26. @classmethod
  27. def create_script(cls, tmpdir):
  28. """
  29. Create a simple script, foo-script.py
  30. Note that the script starts with a Unix-style '#!' line saying which
  31. Python executable to run. The wrapper will use this line to find the
  32. correct Python executable.
  33. """
  34. script = cls.prep_script(cls.script_tmpl)
  35. with (tmpdir / cls.script_name).open('w') as f:
  36. f.write(script)
  37. # also copy cli.exe to the sample directory
  38. with (tmpdir / cls.wrapper_name).open('wb') as f:
  39. w = resources.files('setuptools').joinpath(cls.wrapper_source).read_bytes()
  40. f.write(w)
  41. def win_launcher_exe(prefix):
  42. """A simple routine to select launcher script based on platform."""
  43. assert prefix in ('cli', 'gui')
  44. if platform.machine() == "ARM64":
  45. return f"{prefix}-arm64.exe"
  46. else:
  47. return f"{prefix}-32.exe"
  48. class TestCLI(WrapperTester):
  49. script_name = 'foo-script.py'
  50. wrapper_name = 'foo.exe'
  51. wrapper_source = win_launcher_exe('cli')
  52. script_tmpl = textwrap.dedent(
  53. """
  54. #!%(python_exe)s
  55. import sys
  56. input = repr(sys.stdin.read())
  57. print(sys.argv[0][-14:])
  58. print(sys.argv[1:])
  59. print(input)
  60. if __debug__:
  61. print('non-optimized')
  62. """
  63. ).lstrip()
  64. def test_basic(self, tmpdir):
  65. """
  66. When the copy of cli.exe, foo.exe in this example, runs, it examines
  67. the path name it was run with and computes a Python script path name
  68. by removing the '.exe' suffix and adding the '-script.py' suffix. (For
  69. GUI programs, the suffix '-script.pyw' is added.) This is why we
  70. named out script the way we did. Now we can run out script by running
  71. the wrapper:
  72. This example was a little pathological in that it exercised windows
  73. (MS C runtime) quoting rules:
  74. - Strings containing spaces are surrounded by double quotes.
  75. - Double quotes in strings need to be escaped by preceding them with
  76. back slashes.
  77. - One or more backslashes preceding double quotes need to be escaped
  78. by preceding each of them with back slashes.
  79. """
  80. self.create_script(tmpdir)
  81. cmd = [
  82. str(tmpdir / 'foo.exe'),
  83. 'arg1',
  84. 'arg 2',
  85. 'arg "2\\"',
  86. 'arg 4\\',
  87. 'arg5 a\\\\b',
  88. ]
  89. proc = subprocess.Popen(
  90. cmd,
  91. stdout=subprocess.PIPE,
  92. stdin=subprocess.PIPE,
  93. text=True,
  94. encoding="utf-8",
  95. )
  96. stdout, _stderr = proc.communicate('hello\nworld\n')
  97. actual = stdout.replace('\r\n', '\n')
  98. expected = textwrap.dedent(
  99. r"""
  100. \foo-script.py
  101. ['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b']
  102. 'hello\nworld\n'
  103. non-optimized
  104. """
  105. ).lstrip()
  106. assert actual == expected
  107. def test_symlink(self, tmpdir):
  108. """
  109. Ensure that symlink for the foo.exe is working correctly.
  110. """
  111. script_dir = tmpdir / "script_dir"
  112. script_dir.mkdir()
  113. self.create_script(script_dir)
  114. symlink = pathlib.Path(tmpdir / "foo.exe")
  115. symlink.symlink_to(script_dir / "foo.exe")
  116. cmd = [
  117. str(tmpdir / 'foo.exe'),
  118. 'arg1',
  119. 'arg 2',
  120. 'arg "2\\"',
  121. 'arg 4\\',
  122. 'arg5 a\\\\b',
  123. ]
  124. proc = subprocess.Popen(
  125. cmd,
  126. stdout=subprocess.PIPE,
  127. stdin=subprocess.PIPE,
  128. text=True,
  129. encoding="utf-8",
  130. )
  131. stdout, _stderr = proc.communicate('hello\nworld\n')
  132. actual = stdout.replace('\r\n', '\n')
  133. expected = textwrap.dedent(
  134. r"""
  135. \foo-script.py
  136. ['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b']
  137. 'hello\nworld\n'
  138. non-optimized
  139. """
  140. ).lstrip()
  141. assert actual == expected
  142. def test_with_options(self, tmpdir):
  143. """
  144. Specifying Python Command-line Options
  145. --------------------------------------
  146. You can specify a single argument on the '#!' line. This can be used
  147. to specify Python options like -O, to run in optimized mode or -i
  148. to start the interactive interpreter. You can combine multiple
  149. options as usual. For example, to run in optimized mode and
  150. enter the interpreter after running the script, you could use -Oi:
  151. """
  152. self.create_script(tmpdir)
  153. tmpl = textwrap.dedent(
  154. """
  155. #!%(python_exe)s -Oi
  156. import sys
  157. input = repr(sys.stdin.read())
  158. print(sys.argv[0][-14:])
  159. print(sys.argv[1:])
  160. print(input)
  161. if __debug__:
  162. print('non-optimized')
  163. sys.ps1 = '---'
  164. """
  165. ).lstrip()
  166. with (tmpdir / 'foo-script.py').open('w') as f:
  167. f.write(self.prep_script(tmpl))
  168. cmd = [str(tmpdir / 'foo.exe')]
  169. proc = subprocess.Popen(
  170. cmd,
  171. stdout=subprocess.PIPE,
  172. stdin=subprocess.PIPE,
  173. stderr=subprocess.STDOUT,
  174. text=True,
  175. encoding="utf-8",
  176. )
  177. stdout, _stderr = proc.communicate()
  178. actual = stdout.replace('\r\n', '\n')
  179. expected = textwrap.dedent(
  180. r"""
  181. \foo-script.py
  182. []
  183. ''
  184. ---
  185. """
  186. ).lstrip()
  187. assert actual == expected
  188. class TestGUI(WrapperTester):
  189. """
  190. Testing the GUI Version
  191. -----------------------
  192. """
  193. script_name = 'bar-script.pyw'
  194. wrapper_source = win_launcher_exe('gui')
  195. wrapper_name = 'bar.exe'
  196. script_tmpl = textwrap.dedent(
  197. """
  198. #!%(python_exe)s
  199. import sys
  200. f = open(sys.argv[1], 'wb')
  201. bytes_written = f.write(repr(sys.argv[2]).encode('utf-8'))
  202. f.close()
  203. """
  204. ).strip()
  205. def test_basic(self, tmpdir):
  206. """Test the GUI version with the simple script, bar-script.py"""
  207. self.create_script(tmpdir)
  208. cmd = [
  209. str(tmpdir / 'bar.exe'),
  210. str(tmpdir / 'test_output.txt'),
  211. 'Test Argument',
  212. ]
  213. proc = subprocess.Popen(
  214. cmd,
  215. stdout=subprocess.PIPE,
  216. stdin=subprocess.PIPE,
  217. stderr=subprocess.STDOUT,
  218. text=True,
  219. encoding="utf-8",
  220. )
  221. stdout, stderr = proc.communicate()
  222. assert not stdout
  223. assert not stderr
  224. with (tmpdir / 'test_output.txt').open('rb') as f_out:
  225. actual = f_out.read().decode('ascii')
  226. assert actual == repr('Test Argument')