python执行linux命令超时

fiy 其他 261

回复

共3条回复 我来回复
  • fiy的头像
    fiy
    Worktile&PingCode市场小伙伴
    评论

    执行Linux命令超时可能由于多种原因引起,例如命令执行时间过长、命令被阻塞或网络延迟等。在Python中,可以通过一些方法来解决执行Linux命令超时的问题。

    一、使用subprocess模块的timeout参数
    subprocess模块是Python中处理外部命令的模块,可以通过设置timeout参数来控制命令执行的超时时间。使用subprocess.run()或subprocess.Popen()函数执行命令时,可以添加timeout参数,指定命令执行的最长时间。当超过指定的时间后,命令会被强制终止。

    下面是一个使用subprocess模块设置命令超时时间的示例代码:

    “`python
    import subprocess

    command = ‘your command here’
    try:
    result = subprocess.run(command, shell=True, timeout=10, check=True, capture_output=True)
    # 指定timeout参数为10秒
    # 其他参数说明:
    # shell=True :允许在子shell中运行命令
    # check=True :若命令执行失败,将引发CalledProcessError异常
    # capture_output=True :将命令输出捕获到result.stdout中
    print(result.stdout.decode())
    except subprocess.TimeoutExpired:
    print(‘Command timeout’)
    except subprocess.CalledProcessError as e:
    print(f’Command failed with return code {e.returncode}:\n{e.stderr.decode()}’)
    “`

    二、使用select模块的timeout参数
    另一种处理命令超时的方法是使用select模块。select模块提供了一种高效的I/O多路复用机制,可以监控多个文件描述符的状态,包括输入、输出和错误等。我们可以利用它来检测命令执行时的超时情况。

    下面是一个使用select模块设置命令超时时间的示例代码:

    “`python
    import subprocess
    import select

    def run_command_with_timeout(command, timeout):
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # 创建子进程执行命令

    while True:
    ready, _, _ = select.select([process.stdout, process.stderr], [], [], timeout)
    # 使用select模块检测子进程标准输出和错误输出是否就绪

    if not ready:
    process.terminate()
    # 若就绪时间超过指定timeout时间,则终止命令执行
    return None, ‘Command timeout’

    stdout = process.stdout.readline().decode().strip()
    stderr = process.stderr.readline().decode().strip()
    # 读取命令输出的一行

    if stdout:
    print(stdout)
    if stderr:
    print(stderr)

    if process.poll() is not None:
    break
    # 命令执行完成后退出循环

    return process.returncode, None

    command = ‘your command here’
    timeout = 10
    returncode, error = run_command_with_timeout(command, timeout)
    if error:
    print(error)
    “`

    以上是两种常用的处理Python执行Linux命令超时的方法,根据实际需求和情况选择合适的方法来解决问题。希望对你有帮助!

    2年前 0条评论
  • worktile的头像
    worktile
    Worktile官方账号
    评论

    当 Python 执行 Linux 命令超时时,可以采取以下几种解决方法:

    1. 使用 subprocess 模块设置超时时间:subprocess 模块是 Python 提供的用于执行外部命令的模块,通过设置超时时间可以控制命令执行的时间。可以使用 Popen 函数创建一个子进程,并设置超时时间。如果命令执行超过设定的超时时间,可以捕捉到 TimeoutExpired 异常,并进行相应的处理。

    下面是一个例子:

    “`python
    import subprocess

    # 执行命令,并设置超时时间为10秒
    try:
    output = subprocess.run(‘command’, timeout=10, capture_output=True, text=True)
    print(output.stdout)
    except subprocess.TimeoutExpired:
    print(“Command execution timed out”)
    “`

    2. 使用 signal 设置超时时间:可以使用 signal 模块中的 alarm 函数设置超时时间。通过在执行命令之前设置一个定时器,在超时时间到达后,触发一个信号,并在信号处理函数中进行相应的处理。

    下面是一个例子:

    “`python
    import subprocess
    import signal

    def timeout_handler(signum, frame):
    raise TimeoutError

    signal.signal(signal.SIGALRM, timeout_handler)
    signal.alarm(10) # 设置超时时间为10秒

    try:
    output = subprocess.check_output(‘command’, shell=True)
    print(output)
    except TimeoutError:
    print(“Command execution timed out”)
    finally:
    signal.alarm(0) # 清除定时器
    “`

    3. 使用线程设置超时时间:可以使用 threading 模块创建一个执行命令的线程,并设置一个定时器,在超时时间到达后,终止线程的执行,并进行相应的处理。

    下面是一个例子:

    “`python
    import subprocess
    import threading

    def run_command(cmd):
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, error = process.communicate()
    print(output)

    cmd = ‘command’
    timeout_seconds = 10

    # 创建一个线程执行命令,并设置超时时间
    thread = threading.Thread(target=run_command, args=(cmd,))
    thread.start()
    thread.join(timeout_seconds) # 等待线程执行结束,最多等待超时时间

    if thread.is_alive():
    thread.terminate() # 终止线程的执行
    thread.join()
    print(“Command execution timed out”)
    “`

    4. 使用第三方库:还有一些第三方的库可以用于执行命令并设置超时时间,如 `sh`、`plumbum` 等。这些库提供了更加简洁和直观的方式来执行命令,并且可以很方便地设置超时时间。可以根据自己的需求选择合适的库来解决问题。

    5. 检查命令执行时间:也可以通过在执行命令之后检查命令的执行时间来确定是否超时。可以在执行命令之前记录当前时间,然后在命令执行完成后计算执行时间,如果超过设定的超时时间,进行相应的处理。

    下面是一个例子:

    “`python
    import time
    import subprocess

    start_time = time.time()
    output = subprocess.check_output(‘command’, shell=True)
    end_time = time.time()

    execution_time = end_time – start_time # 计算命令执行时间

    if execution_time > 10: # 判断是否超时
    print(“Command execution timed out”)
    else:
    print(output)
    “`

    以上是几种解决 Python 执行 Linux 命令超时的方法,可以根据实际情况选择合适的方法来解决问题。

    2年前 0条评论
  • 不及物动词的头像
    不及物动词
    这个人很懒,什么都没有留下~
    评论

    在Python中执行Linux命令超时可以通过多种方式实现。下面将使用三种不同的方法来讲解如何在Python中执行Linux命令并设置超时。

    方法一:使用subprocess模块执行命令并设置超时
    “`python
    import subprocess
    import shlex
    import time
    import signal

    def run_command_with_timeout(command, timeout):
    # 定义命令超时时执行的函数
    def timeout_handler(signum, frame):
    raise TimeoutError(“Command execution timed out”)

    # 创建子进程并执行命令
    process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)

    # 设置超时信号和处理函数
    signal.signal(signal.SIGALRM, timeout_handler)
    signal.alarm(timeout)

    try:
    # 等待命令执行完毕
    stdout, stderr = process.communicate()

    # 取消超时信号
    signal.alarm(0)

    # 返回命令执行结果
    returncode = process.returncode
    return stdout, stderr, returncode

    except TimeoutError:
    # 超时处理
    process.kill()
    stdout, stderr = process.communicate()
    return stdout, stderr, -1
    “`
    使用上述方法,可以通过`run_command_with_timeout(command, timeout)`函数来执行命令。其中,`command`参数是要执行的命令,`timeout`参数是设置的超时时间(单位为秒)。函数返回命令的输出结果、错误信息和返回码。

    方法二:使用threading模块执行命令并设置超时
    “`python
    import subprocess
    import threading

    def run_command_with_timeout(command, timeout):
    # 定义命令执行函数
    def run_command(command):
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    stdout, stderr = process.communicate()
    return stdout, stderr, process.returncode

    # 创建子线程并执行命令
    thread = threading.Thread(target=run_command, args=(command,))
    thread.start()

    # 等待命令执行完毕,超时则抛出异常
    thread.join(timeout)

    if thread.is_alive():
    # 超时处理
    thread.join()
    return None, None, -1
    else:
    # 返回命令执行结果
    return thread._result
    “`
    通过上述方法,可以通过`run_command_with_timeout(command, timeout)`函数来执行命令。其中,`command`参数是要执行的命令,`timeout`参数是设置的超时时间(单位为秒)。函数返回命令的输出结果、错误信息和返回码。

    方法三:使用paramiko模块在远程服务器上执行命令并设置超时
    “`python
    import paramiko
    import time
    import select

    def run_command_with_timeout(command, timeout, host, username, password, port=22):
    # 创建SSH客户端
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # 连接远程服务器
    ssh.connect(host, port, username, password)

    # 创建SSH会话
    channel = ssh.get_transport().open_session()
    channel.settimeout(timeout)

    # 执行命令
    channel.exec_command(command)

    # 等待命令执行完毕,超时则抛出异常
    start_time = time.time()
    while True:
    if channel.exit_status_ready():
    break

    current_time = time.time()
    if current_time – start_time > timeout:
    channel.close()
    ssh.close()
    raise TimeoutError(“Command execution timed out”)

    time.sleep(0.1)

    # 获取命令执行结果
    stdout = []
    stderr = []
    while True:
    if channel.recv_ready():
    stdout.append(channel.recv(1024).decode(“utf-8”))
    if channel.recv_stderr_ready():
    stderr.append(channel.recv_stderr(1024).decode(“utf-8″))
    if channel.exit_status_ready():
    break

    # 关闭SSH会话和连接
    channel.close()
    ssh.close()

    return ”.join(stdout), ”.join(stderr), channel.recv_exit_status()
    “`
    通过上述方法,可以通过`run_command_with_timeout(command, timeout, host, username, password, port)`函数在远程服务器上执行命令并设置超时。其中,`command`参数是要执行的命令,`timeout`参数是设置的超时时间(单位为秒),`host`参数是远程服务器的主机地址,`username`和`password`参数是登录远程服务器的用户名和密码,`port`参数是SSH连接的端口号。函数返回命令的输出结果、错误信息和返回码。
    “`事例:
    command = “ls -l”
    timeout = 5

    stdout, stderr, returncode = run_command_with_timeout(command, timeout)

    if returncode == 0:
    print(“命令执行成功”)
    print(“输出结果:”, stdout)
    else:
    print(“命令执行失败”)
    print(“错误信息:”, stderr)

    2年前 0条评论
注册PingCode 在线客服
站长微信
站长微信
电话联系

400-800-1024

工作日9:30-21:00在线

分享本页
返回顶部