所以我有这个简单的 POC
import subprocess
proc = subprocess.run('cmd', timeout=1, shell=True, capture_output=True)
在给定的时间间隔(本例中为 1 秒)之后,它不会引发 TimeoutError
subprocess.run()
中的超时标志在 Linux 中工作得很好,但在 Windows 中似乎会产生错误
例如
import subprocess
proc = subprocess.run('ping -n 10 127.0.0.1', shell=True, capture_output=True, timeout=1)
似乎不会引发超时错误直到命令完成后
评论太长...作为仅供参考
PS C:\Users\OWNER> type .\Documents\t.py
import subprocess
roc = subprocess.run('ping -n 10 127.0.0.1', shell=True, capture_output=True, timeout=1)
PS C:\Users\OWNER> python .\Documents\t.py
python : Traceback (most recent call last):
At line:1 char:1
+ python .\Documents\t.py
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Traceback (most recent call last)::String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
File "C:\Users\OWNER\Documents\t.py", line 2, in <module>
roc = subprocess.run('ping -n 10 127.0.0.1', shell=True, capture_output=True, timeout=1)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2032.0_x64__qbz5n2kfra8p0\Lib\subprocess.py", line 550, in run
stdout, stderr = process.communicate(input, timeout=timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2032.0_x64__qbz5n2kfra8p0\Lib\subprocess.py", line 1209, in communicate
stdout, stderr = self._communicate(input, endtime, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2032.0_x64__qbz5n2kfra8p0\Lib\subprocess.py", line 1630, in _communicate
raise TimeoutExpired(self.args, orig_timeout)
subprocess.TimeoutExpired: Command 'ping -n 10 127.0.0.1' timed out after 1 seconds