仅在从命令行调用脚本时运行代码 [英] Run code only if script called from the command line
问题描述
所以,当我从命令行调用我的脚本,我想要它接受一个int,并做一些与值:
So when I call my script from the command line, I want it to take in an int and do something with the value:
ruby script.rb
puts ARGV[0], etc...
但是,无论何时加载或需要脚本,并且不从命令行调用,我想完全跳过这部分代码。如何检测脚本是通过命令行调用,还是刚刚加载?谢谢!
However, whenever the script is loaded or required and not called from command line, I want to completely skip this part of the code. How can I detect whether the script has been called via command line, or just loaded? Thanks!
推荐答案
通常将它放在脚本底部:
It is common to put this at the bottom of your script:
if __FILE__==$0
# this will only run if the script was the main, not load'd or require'd
end
因为我喜欢看到文件顶部的主要操作,所以我通常把 def run!
作为文件中的第一个方法,然后使用以下命令结束文件:
Because I like to see the main action at the top of my file, I usually put a def run!
as the first method in the file and then end the file with:
run! if __FILE__==$0
这篇关于仅在从命令行调用脚本时运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!