我有一个类似的命令:
(clojure.java.shell/sh "curl" "https://somesite.com" "-F" "file=@somefile.txt")
我想创建一个函数,该函数将运行我提供的标准Shell命令...类似这样的东西:
(defn run-shell-command [command]
(clojure.java.shell/sh (clojure.string/split command #" ")))
这样我可以这样称呼它:
(run-shell-command "curl https://somesite.com -F file=@somefile.txt")
但这会抛出:
Unhandled java.lang.IllegalArgumentException
No value supplied for key: ["curl" "https://somesite.com" "-F" "file=@somefile.txt"]
我如何进行这项工作?
(当然,对于如何执行此操作,还有更好的主意)
答案 0 :(得分:2)
您的问题是初学者中最常见的问题:如果我们有一个接受参数的函数,我们如何在这些参数的列表上应用该函数?
(defn f [a b c] (+ a b c))
(def args [1 2 3])
如上所述,答案是 apply 方法。该方法将函数应用于参数列表。因此,在上面的示例中:
(= (f 1 2 3)
(apply f args))
即
(defn run-shell-command [command]
(apply clojure.java.shell/sh (clojure.string/split command #" ")))
答案 1 :(得分:1)
您还可以使用基础命令处理器来处理字符串。例如。使用bash:
#include <iostream>
using namespace std;
//prototypes
int prompt(int sum, int count );
float average(int sum, int count);
void result(float avg);
int main()
{
int num;
cout << "Welcome to Keith's Averaging program";
cout << endl;
int prompt();
int average (int sum, int count);
void result (float avg);
return 0;
}
//Prototype Definitions
//get numbers from users
int prompt()
{
int num, sum, count;
cout << "Enter numbers and I will Average them." << endl;
cout << "Please enter a number: ";
cin >> num;
sum = sum + num;
if(num == 0)
{
cout << "Guess you don't want an average";
cout << endl;
cout << "Goodbye";
}
for(count=0; num !=0; count++)
{
cout << "Please enter a positive number, enter zero to compute the avg: ";
cin >> num;
if(num < 0)
{
cout << "Enter a positive number:";
cin >> num;
}
sum = sum + num;
}
...将其包装在函数中,并根据需要隐藏命令处理器:
(clojure.java.shell/sh "bash" "-c" command)
然后您可以使用任何bash shell命令。例如
(defn run-shell-command [command]
(clojure.java.shell/sh "bash" "-c" command))