大家好! 我正在使用一些更复杂的 python 脚本,我需要使用子进程来使函数执行或 shell 执行超时。
我从这里找到了一个我喜欢并想使用的片段https://medium.com/@chaoren/how-to-timeout-in-python-726002bf2291
import subprocess
r = subprocess.run(['echo', 'hello timeout'], timeout=5)
print(
f'''type(r)={type(r)},
r.args={r.args},
r.returncode={r.returncode},
r.stdout={r.stdout},
r.stderr={r.stderr}'''
)
try:
r = subprocess.run(['ping', 'www.google.com'], timeout=5)
except subprocess.TimeoutExpired as e:
print(e)
当我尝试执行这个文件时,我得到以下内容
Traceback (most recent call last):
File "threadTest.py", line 2, in <module>
r = subprocess.run(['echo', 'hello timeout'], timeout=5)
File "C:\DevOps\Tools\python3.7\lib\subprocess.py", line 453, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\DevOps\Tools\python3.7\lib\subprocess.py", line 756, in __init__
restore_signals, start_new_session)
File "C:\DevOps\Tools\python3.7\lib\subprocess.py", line 1155, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
一个用户在这里遇到了类似的问题,但这对我没有帮助 python: trouble with Popen FileNotFoundError: [WinError 2]
我正在使用 python3.7 和 windows 并以管理员身份运行。
这里有什么明显的我遗漏了吗?我注意到很奇怪的一件事是我的输出错误中的小写“lib”,但在我的路径中“Lib”是大写的。但我不认为这是一个问题,因为它仍然能够读取这个文件。
我将不胜感激任何帮助或见解!感谢您抽出宝贵时间。