如何在没有生成任何数据的情况下终止长时间运行的脚本,我尝试通过paramiko modu在windows控制台中按Ctrl+C

2024-04-25 21:14:01 发布

您现在位置:Python中文网/ 问答频道 /正文

这真的很有趣。 我的linux机器上有以下脚本:

睡眠.py

import time
from datetime import datetime
print(datetime.now())
time.sleep(20)
print('Over!')
print(datetime.now())

循环.py

import time
for i in range(20):
    time.sleep(1)
    print(i)

如果我通过PuTTY或gitbash登录,我可以通过ctrl+c直接终止它们。 但当我尝试在Windows控制台上运行Python脚本时:

测试.py

def ssh_pty_command(cmd, ip, username, passwd=None, key_filename=None):
    """run ssh.exec_command with realtime output and return exit_code."""
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        logging.debug('Connecting to remote server {}...'.format(ip))
        ssh.connect(ip, 22, username, password=passwd,
                    key_filename=key_filename, timeout=5)
        stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True)
        logging.info('ssh_In: {}'.format(cmd))
        # print '$: {}'.format(cmd)
        for line in iter(stdout.readline, ""):
            logging.info('ssh_Out: {}'.format(
                line.rstrip('\n').encode('utf-8')))
        for err in iter(stderr.readline, ""):
            logging.error('ssh_Error: {}'.format(
                err.rstrip().encode('utf-8')))
        exit_code = stdout.channel.recv_exit_status()
        logging.debug('Task exit with code {}.\n'.format(exit_code))
        return exit_code
    except Exception as err:
        logging.error('*** Caught SSH exception: %s: %s' %
                      (err.__class__, err))
        raise
    finally:
        ssh.close()

  ssh_pty_command('python loop.py',ip,username)
  ssh_pty_command('python sleep.py',ip,username)

当我按ctrl+c时,loop.py立即终止,但是sleep.py等待time.sleep(20)完成,然后终止执行。 如何立即终止sleep.py

注意我确实尝试在函数的exec_command方法中使用get_pty=True,但没有任何帮助。 我想这应该和帕拉米科发出的信号有关,但不知道该往哪里挖。。。你知道吗


Tags: pyipcmdformatdatetimetimeloggingexit
1条回答
网友
1楼 · 发布于 2024-04-25 21:14:01

Ctrl+C发出中断信号。Python解释器定期检查中断,并在检测到中断时引发KeyboardInterrupt异常。你知道吗

当Paramiko正在等待套接字上的传入数据时,中断检查可能会暂停(只是猜测)。因此,如果远程命令不产生任何输出,则不能中断本地脚本。你知道吗

您的loop.py使用print(i)生成一个输出,因此您的本地Python脚本可以在处理输出时中断。你知道吗

无论如何,不能中断的不是远程脚本,而是本地脚本。所以它可能与time.sleep本身没有任何关系。你知道吗

另请参见:


如果您实际上不想等待命令完成,那么您的问题实际上不是关于Python(或Paramiko),而是关于Linux。见Execute remote commands, completely detaching from the ssh connection。你知道吗

相关问题 更多 >