gpt4 book ai didi

Ruby - 更新运行脚本

转载 作者:数据小太阳 更新时间:2023-10-29 07:35:27 26 4
gpt4 key购买 nike

是否可以中断当前运行的 Ruby 脚本,更新它,然后继续运行它?

例如说你有脚本:

(0..10).each do |x|
puts x
end

你能不能打断它,把它修改成第二行:

   puts x * 2

然后继续执行?

(假设我们忽略了中断时间太短等琐碎的参数)

最佳答案

如果你真的想停止进程,你可以trap中断信号,将当前进度写入文件,然后在启动备份时查找该文件:

progress_file = './script_progress.txt'
x = if File.exists?(progress_file)
File.read(progress_file).to_i
else
0
end

Signal.trap("INT") {
File.open(progress_file, 'w') { |f| f.write(x.to_s) }
exit
}

while x <= 10 do
puts x
x += 1

sleep(1)
end

结果:

$ rm script_progress.txt 
$ ruby example.rb
0
1
2
3
^C$ cat script_progress.txt
4
# modify example.rb here, changing `puts x` to `puts x * 2`
$ ruby example.rb
8
10
12
14
16
18
20

你也可以使用 at_exit在脚本退出时随时写入文件(即使它刚刚正常完成):

progress_file = './script_progress.txt'
x = if File.exists?(progress_file)
File.read(progress_file).to_i
else
0
end

at_exit do
File.open(progress_file, 'w') { |f| f.write(x.to_s) }
end

while x <= 10 do
puts x
x += 1

sleep(1)
end

结果:

$ ruby example.rb 
0
1
2
3
4
^Cexample.rb:16:in `sleep': Interrupt
from example.rb:16:in `<main>'

# modify example.rb to double the output again
$ ruby example.rb
10
12
14
16
18
20

如果您希望进程继续运行,但只是为了能够切换不同的功能,您可以使用 Process.kill 发送自定义信号:

pid = fork do
Signal.trap("USR1") {
$double = !$double
}

(0..10).each do |x|
puts $double ? x * 2 : x

sleep(1)
end
end

Process.detach(pid)
sleep(5)
Process.kill("USR1", pid)
sleep(6)

结果:

$ ruby example.rb 
0
1
2
3
4
10
12
14
16
18
20

您可以使用它来告诉 ruby​​ 再次加载文件:

File.open('print_number.rb', 'w') do |file|
file.write <<-contents
def print_number(x)
puts x
end
contents
end

pid = fork do
load './print_number.rb'
Signal.trap("USR1") {
load './print_number.rb'
}

(0..10).each do |x|
print_number(x)

sleep(1)
end
end

Process.detach(pid)
sleep(5)
File.open('print_number.rb', 'w') do |file|
file.write <<-contents
def print_number(x)
puts x * 2
end
contents
end
Process.kill("USR1", pid)
sleep(6)

结果:

$ ruby example.rb 
0
1
2
3
4
10
12
14
16
18
20

关于Ruby - 更新运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45663154/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com