The objective is to have two simple ways to source some code, say func.R, containing a function. Calling R CMD BATCH func.R
initializes the function and evaluates is. Within a session, issuing source("func.R")
simply initializes the function. Any idea?
The Reason Behind if __name__ == '__main__' in Python You might have seen this one before: the syntax which often gets ignored because it doesn't seem to hinder the execution of your code. It may not seem necessary, but that's only if you're working with a single Python file.
Python files can act as either reusable modules, or as standalone programs. if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.
In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.
I think that the interactive()
function might work.
This function returns TRUE
when R is being used interactively and FALSE
otherwise. So just use if (interactive())
i.e. the equivalent is
if (!interactive()) { main() }
Another option is:
#!/usr/bin/Rscript # runs only when script is run by itself if (sys.nframe() == 0){ # ... do main stuff }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With