bpo-31961: subprocess now accepts path-like args (GH-4329)

Allow os.PathLike args in subprocess APIs.
diff --git a/Lib/subprocess.py b/Lib/subprocess.py
index 93635ee..2723bc9 100644
--- a/Lib/subprocess.py
+++ b/Lib/subprocess.py
@@ -1097,7 +1097,12 @@
             assert not pass_fds, "pass_fds not supported on Windows."
 
             if not isinstance(args, str):
-                args = list2cmdline(args)
+                try:
+                    args = os.fsdecode(args)  # os.PathLike -> str
+                except TypeError:  # not an os.PathLike, must be a sequence.
+                    args = list(args)
+                    args[0] = os.fsdecode(args[0])  # os.PathLike -> str
+                    args = list2cmdline(args)
 
             # Process startup details
             if startupinfo is None:
@@ -1369,7 +1374,10 @@
             if isinstance(args, (str, bytes)):
                 args = [args]
             else:
-                args = list(args)
+                try:
+                    args = list(args)
+                except TypeError:  # os.PathLike instead of a sequence?
+                    args = [os.fsencode(args)]  # os.PathLike -> [str]
 
             if shell:
                 # On Android the default shell is at '/system/bin/sh'.
diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py
index eee24bb..858a701 100644
--- a/Lib/test/test_subprocess.py
+++ b/Lib/test/test_subprocess.py
@@ -1475,6 +1475,37 @@
                              env=newenv)
         self.assertEqual(cp.returncode, 33)
 
+    def test_run_with_pathlike_path(self):
+        # bpo-31961: test run(pathlike_object)
+        class Path:
+            def __fspath__(self):
+                # the name of a command that can be run without
+                # any argumenets that exit fast
+                return 'dir' if mswindows else 'ls'
+
+        path = Path()
+        if mswindows:
+            res = subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
+        else:
+            res = subprocess.run(path, stdout=subprocess.DEVNULL)
+
+        self.assertEqual(res.returncode, 0)
+
+    def test_run_with_pathlike_path_and_arguments(self):
+        # bpo-31961: test run([pathlike_object, 'additional arguments'])
+        class Path:
+            def __fspath__(self):
+                # the name of a command that can be run without
+                # any argumenets that exits fast
+                return sys.executable
+
+        path = Path()
+
+        args = [path, '-c', 'import sys; sys.exit(57)']
+        res = subprocess.run(args)
+
+        self.assertEqual(res.returncode, 57)
+
     def test_capture_output(self):
         cp = self.run_python(("import sys;"
                               "sys.stdout.write('BDFL'); "