I want to step through an R script. I saw the "debug" command while searching for how to do this but that seems to only apply to functions. This script doesn't have any functions.
The "browser" command looked promising so I put "browser()" as the first line of my script but it didn't seem to do anything when I ran it.
How do I get the script to pause on the first line so I can step through it?
I was racking my brain trying to figure this out (stepping through a script without a specific function to call) in RStudio's IDE Version 0.98.1102.
Solution for a new script in RStudio:
Create a new R script (ctrl+shift+n)
Enter code in the file
Set a break point by
a) clicking left of the code line number where you want to set a break point (red dot) or
b) adding browser() to the code line where you want to set a break point
Save the file
Enter debugging mode and source the file by
a) checking the Source on Save box (above the Source window) and then saving the file,
b) clicking the Source button at the top-right of the Source window,
c) entering debugSource("<yourfilename>") + enter in the Console, or
d) entering ctrl+shift+s
Go through the debugging process
For more steps on debugging in RStudio, see this help file
(dated April 23, 2015 12:59).
I'm partial to RStudio, so I recommend the following:
Download RStudio
Open your R Script
put your cursor on the first line
click ctrl + enter (PC/Linux) or command + return (Mac)
repeat!
A nice feature of RStudio is that RStudio server can run great on a headless server. You then connect to the server via http in a web browser on your local machine. I use this configuration when running R on EC2 instances. RStudio maintains state so if I lose internet access on my train ride, when I get signal back RStudio picks up exactly where I left off and my remote machine has no idea that I disconnected and reconnected. Note that RStudio server is currently only supported on FC/CentOS and Debian/Ubuntu. Although it may compile under other variants of *nix.
One popular way is to do this from your 'IDE' or editor -- Emacs / ESS do it very well, others do it too.
The basic idea is that you send either the line under the cursors, or function, or block, ... to the associated R process. Several other editors support this, including RStudio. My preference is still with ESS, but I am sure you can find something suitable.
Lastly, browser() et al can do that from within the R process but it is a little less pointy-clickety. Read the documentation, or books like Chambers "Software for Data Analysis" (Springer, 2008).
For an R only solution, which evaluates complete expressions rather than individual lines, try this:
sourcep <- function(file){
coms <- parse(file)
for (i in seq_along(coms)){
print(coms[[i]])
eval(coms[[i]],envir=.GlobalEnv)
mess <- paste("Expression",i,"of",length(coms),"parsed. Press <return> to continue.")
cat(mess)
readLines(n=1)
}
}
You call this as you would call source (though this is much more basic and doesn't include any of its options). Basically, it uses parse to create a list of the parsed, but unevaluated expressions from your source file, then iterates through this list to print the expression, evaluate it in the global environment and then put a message to indicate the progess. The final line is the one that creates the pausing: a call to read a single line from stdin().
You mention in a comment that you run your code with Rscript, but to debug you need to run it interactively. In other words, to get browser to "work", start up a regular R console and source your script. Since the first line of the script is browser(), you'll immediately get back to the prompt, at which you can use "n" to single step through the code. But, since it's a full-blown R prompt, you can also check or change any variable value just by typing its name or assigning to it. (Or indeed, invoke arbitrary R functions.)
As suggested in another answer, inserting browser() at the beginning of your script, getting an interactive session by running R rather than Rscript, and then using source('myscript.Rscript') from R will do the trick if your script does not require commadline arguments (e.g. like those processed by argparse).
If you do need to run with commandline args, you can simply invoke R with the --args options (e.g. R --no-restore --no-save --args <your commandline args here>) and the sourced script will see the arguments as if it had been invoked using Rscript. There are other solutions to the question of how to pass commandline args to source, but they don't target this specific use case where source will be called only once.
Related
I've been wondering how I could do some of these cool customization options for the terminal on a Mac and I came across lolcat.
However, I can't seem to find an answer as to how to add this into my bashrc (FYI: I'm using zsh now just in case that makes a difference as to which file to add my customizations in) I have tried what many others have suggested, which was just typing zsh | lolcat into the terminal to get rainbow output in the current session, but I was wondering how I can have this every time I start a terminal session.
Also, I'm not sure if this is a bug or if there's something wrong with my terminal settings, but when I use a command with lolcat, I get an output like this:
karenlee#Karens-MBP ~ % Documents
Downloads
Library
Movies
Music
Pictures
Postman
Public
38;5;48m
karenlee#Karens-MBP ~ % 38;5;48m
The colors look right, but as you can see, when I type the ls command on the command line, it disappears and the output also gets messy. It also seems like there's extra lines of 38;5;48m which are appearing. And it also seemed like many of the gems that are installed with lolcat have deprecated; is there another alternative to lolcat that plays nicely with macOS Catalina?
I made a shell extension for the world's fastest website generator that I make called Nift. It has an easter egg where you can turn on lolcat output for most things with lolcat.on (after starting the shell with eg. nift sh). You will even get rainbow output when pressing tab to get possible completion options, I doubt you get that with any other suggested solutions.
The shell extension is for f++ which is the in-built scripting language, which has these functions and these types available. But anything it doesn't recognise is run as a system call using the (probably primary/default) shell on your machine (hence calling it a shell extension in REPL shell mode).
Nift will look for a version of lolcat installed on your machine and otherwise use an in-built version of it which should be the world's fastest (it's near identical to my c++ implementation lolcat-cc which is the world's fastest). I highly recommend installing lolcat-cc (or another version of lolcat) on top of Nift though as otherwise you are frequently running the ~5mb Nift binary for basically all system calls, instead of a <1mb binary for lolcat.
f++ is somewhat of an interesting scripting language as well. Take this script for example which creates and deletes 100k empty text files. On my machine this runs in ~3.5 seconds whereas this Bash script doing essentially the same thing takes more like 3 minutes!! Some of the cool things you might already notice from that f++ script is you can expand variables inside strings, you can define variables with types, you can expand variables in to multiple parameters with function calls, you can have LOTS more than 10k input parameters for function calls (should be able to have millions!).
You can find some more information about the Nift REPLs (including shortcuts for different platforms) here.
If you need to define shell variables (not through f++ but the underlying shell) then you will need to do blocks of code using the sys/system function. You can also do blocks of code for Lua(JIT) and ExprTk similarly as they are both embedded in to Nift. You can use both Lua and ExprTk with accessing/modifying f++ variables as well..
So to get this shell (extension). Install Nift through a package manager or clone, make and install off GitHub. Enter nift sh in to your terminal to start the Nift f++ shell extension, then enter lolcat.on to turn on rainbow output.
I try to make some script for gimp, using script-fu, scheme.
Naturally, as a beginner, there are lots of errors and misunderstandings.
Now I'm looking for a way to debug those scripts.
I found (gimp-message), but the result does not show up. I'm not aware if there is a possibility to print debug messages to anywhere I could check them.
Generating new images filled with text would probably work ;-) but looks a bit like an overkill.
What ways to debug a script in gimp are there?
There may be a better way, but, the way I do it is to:
open the script fu console (Filters -> Script Fu -> Console)
edit a file (say for example: /Users/jamesanderson/code/scheme/gimp/learn1.scm
type: (load "/Users/jamesanderson/code/scheme/gimp/learn1.scm") into the console
hit enter
edit file for changes
keyboard arrow up (to get get the load function call again without typing)
hit enter
Note this is an extension of my answer based on the comment. When going beyond the simple proof of concept scripts like the above, its important to know that that console retains state between calls. So for instance, if we run this scheme script:
(define jea-test-img-id nil)
(define (jea-find-test-img)
(car (gimp-image-list)))
and then go to the console and type:
jea-test-img-id
we get as a result:
> jea-test-img-id
()
which is good, the script initiated the variable as needed and we see the result. So var set in script, console retains state change from script. Now lets change the state in the console:
(set! jea-test-img-id (jea-find-test-img))
we call a convenience function that grabs the first image ID in the active image list and store it in the variable we previously declared (which was then nil). Now lets examine the question again:
jea-test-img-id
then the result:
> jea-test-img-id
1
so high level: when you are working on a script, create working variables that hold the things you want to work on, like image, pxiels, widths etc then piece by piece get the functions working. In the end you may collapse it into one clean function once you have the short snippet pieces.
The output of gimp-message goes to the "Error console" (if you have this dockable dialog setup), otherwise in a warning dialog.
If you are in Linux or OSX, you can also start Gimp from a terminal and use (print ...) calls, they will show in the terminal.
You can make your life easier and write your scripts in Python (easier to learn, and more powerful...). See here for the doc, here for some examples, and here for some debug tricks for Windows.
If you run gimp from the command line with the -c flag, messages are printed in the terminal:
$ gimp -c myfile.xcf
# run my plugin from the GUI menu
My Plugin-Warning: this is a message
Tested with GIMP v2.10.18 see gimp --help for more command line options.
I am using Rstudio and not sure how options "run" and "source" are different.
I tried googling these terms but 'source' is a very common word and wasn't able to get good search results :(
Run and source have subtly different meanings. According to the RStudio documentation,
The difference between running lines from a selection and invoking
Source is that when running a selection all lines are inserted
directly into the console whereas for Source the file is saved to a
temporary location and then sourced into the console from there
(thereby creating less clutter in the console).
Something to be aware of, is that sourcing functions in files makes them available for scripts to use. What does this mean? Imagine you are trying to troubleshoot a function that is called from a script. You need to source the file containing the function, to make the changes available in the function be used when that line in the script is then run.
A further aspect of this is that you can source functions from your scripts. I use this code to automatically source all of the functions in a directory, which makes it easy to run a long script with a single run:
# source our functions
code.dir <- "c:\temp"
code.files = dir(code.dir, pattern = "[.r]")
for (file in code.files){
source(file = file.path(code.dir,file))
}
Sometimes, for reasons I don't understand, you will get different behavior depending on whether you select all the lines of code and press the run the button or go to code menu and chose 'source.' For example, in one specific case, writing a gplot to a png file worked when I selected all my lines of code but the write failed to when I went to the code menu and chose 'source.' However, if I choose 'Source with Echo,' I'm able to print to a png file again.
I'm simply reporting a difference here that I've seen between the selecting and running all your lines and code and going to code menu and choosing 'source,' at least in the case when trying to print a gplot to a png file.
An important implication of #AndyClifton's answer is:
Rstudio breakpoints work in source (Ctrl-Shift-S) but not in run (Ctrl-Enter)
Presumably the reason is that with run, the code is getting passed straight into the console with no support for a partial submission.
You can still use browser() though with run though.
print() to console is supported in debugSource (Ctrl-Shift-S) as well as run.
The "run" button simply executes the selected line or lines. The "source" button will execute the entire active document. But why not just try them and see the difference?
I also just discovered that the encoding used to read the function sourced can also be different if you source the file or if you add the function of the source file to your environment with Ctrl+Enter!
In my case there was a regex with a special character (ยต) in my function. When I imported the function directly (Ctrl+Enter) everything would work, while I had an error when sourcing the file containing this function.
To solve this issue I specified the encoding of the sourced file in the source function (source("utils.R", encoding = "UTF-8")).
Run will run each line of code, which means that it hits enter at the beginning of each line, which prints the output to the console. Source won't print anything unless you source with echo, which means that ggplot won't print to pngs, as another posted mentioned.
A big practical difference between run and source is that if you get an unaccounted for error in source it'll break you out of the code without finishing, whereas run will just pass the next line to the console and keep going. This has been the main practical difference I've seen working on cleaning up other people's scripts.
When using RSTudio u can press the run button in the script section - it will run the selected line.
Next to it you have the re - run button, to run the line again. and the source button next to it will run entire chuncks of code.
I found a video about this topic:
http://www.youtube.com/watch?v=5YmcEYTSN7k
Source/Source with echo is used to execute the whole file whereas Run as far as my personal experience goes executes the line in which your cursor is present.
Thus, Run helps you to debug your code. Watch out for the environment. It will display what's happening in the stack.
To those saying plots do not show. They won't show in Plots console. But you can definitely save the plot to disc using Source in RStudio. Using this snippet:
png(filename)
print(p)
dev.off()
I can confirm plots are written to disc. Furthermore print statements are also outputted to the console
When using Mac OS X including iTerm, I can simply press
Shift+$ and the line in bash that I am currently tiping will get a # added to the beginning and the line returns. I like this very much as it prevents from actually executing that command while still editing it and I don't have to jump to the beginning of the line to insert that # character there.
However, when I log onto our cluster, this functionality is lost. I tried to search for this feature but only found posts about using sed etc. so suggestions which are not for the interactive kind of using bash that I am referring to.
Could somebody please point me to a resource where this functionality is explained (bash-guide?) so I could look up how to make it work when logging in to other machines? Or is this something Mac/iTerm-specific? But then, I would expect it to work also on our cluster, as long as I use my machine of course.
This might work for you
See insert-comment (M-#)
I'd like to be able to write Inquisit scripts in Vim.
In the standard Inquisit application for writing scripts, I can press F1 and it brings up help on the topic related to the word under the cursor.
I'd like to set up the same functionality through Vim.
The help file for Inquisit is stored in a Windows .CHM file.
I figured there must be a set of command-line options for doing a keyword search in a chm file, but I haven't been able to find a complete list of the command-line options, presumably for HH.exe.
I did find HTML Help command-line article from help-info.de with a few pointers, but it does not have a full listing of command-line options.
I also found this discussion on AutoHotKey discussion board. It mentions keyhh.
I also just found a vimscript designed to do exactly what I want
Questions:
Is there a complete list of command-line options for HH.exe?
Is there a better way of going about what I am trying to do?
If you can script in AutoHotkey ,I just found a solution. The idea will be to use VIM to pass reqd. command line-parameters to a compiled Ahk script which will in turn open the help file a/c the data.
In this solution, it will be also assumed that all the keywords that you are to search lie in the Index list (as they do).
To open the Helpfile, then Index tab & search, the following AHK Code works --
Run, %Helpfile% ; your help file
Winwaitactive, ahk_class HH Parent
SendMessage, 0x1330, 1,, SysTabControl321
sleep, 0
SendMessage, 0x130C, 1,, SysTabControl321
Send,+{Home}%1%{Enter}
where %1% is the only command line param passed to the compiled Ahk script.
So, VIM can passe Commandline params as start compiledahk.exe "<Keyword>".