How can I execute system specific commands and get their response in Clojure? For example, let's assume we're on a Linux machine, how can I call top
or free
, and get their results for further processing?
If you need to execute a shell command with Python, there are two ways. You can either use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.
Python Subprocess Run Function The subprocess. run() function was added in Python 3.5 and it is recommended to use the run() function to execute the shell commands in the python program. The args argument in the subprocess. run() function takes the shell command and returns an object of CompletedProcess in Python.
(use '[clojure.java.shell :only [sh]]) (sh "free") (sh "top" "-bn1")
See also: http://clojuredocs.org/clojure_core/clojure.java.shell/sh
You should be able to use the Java Runtime.exec method as follows:
(import 'java.lang.Runtime) (. (Runtime/getRuntime) exec "your-command-line-here")
The Runtime.exec method returns a Process object that you can query to get the standard output etc. as needed.
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