这真的很有趣。 我的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
,但没有任何帮助。
我想这应该和帕拉米科发出的信号有关,但不知道该往哪里挖。。。你知道吗
Ctrl+C发出中断信号。Python解释器定期检查中断,并在检测到中断时引发
KeyboardInterrupt
异常。你知道吗当Paramiko正在等待套接字上的传入数据时,中断检查可能会暂停(只是猜测)。因此,如果远程命令不产生任何输出,则不能中断本地脚本。你知道吗
您的
loop.py
使用print(i)
生成一个输出,因此您的本地Python脚本可以在处理输出时中断。你知道吗无论如何,不能中断的不是远程脚本,而是本地脚本。所以它可能与
time.sleep
本身没有任何关系。你知道吗另请参见:
如果您实际上不想等待命令完成,那么您的问题实际上不是关于Python(或Paramiko),而是关于Linux。见Execute remote commands, completely detaching from the ssh connection。你知道吗
相关问题 更多 >
编程相关推荐