ideawu / ssdb

SSDB - A fast NoSQL database, an alternative to Redis
http://ssdb.io/
BSD 3-Clause "New" or "Revised" License
8.19k stars 1.4k forks source link

Make ssdb-cli more silent when used in a script #1347

Open ghen2 opened 4 years ago

ghen2 commented 4 years ago

Currently ssdb-cli prints banner and prompt on stderr, regulur output on stdout, and errors on stderr. This makes it hard to use in (cron) scripts because you can't just discard stderr to filter unneeded output, or you will miss errors as well.

Below patch is a draft attempt at minimizing output when stdin is not a tty (the code already disables histfile in this case), but it can probably be improved.

An alternative to the "isatty" test would be a --silent command line option to print only errors.

--- tools/ssdb-cli.cpy  2020-02-15 12:22:06.000000000 +0100
+++ tools/ssdb-cli.cpy  2020-05-13 21:59:20.530320745 +0200
@@ -13,6 +13,7 @@
    sys.stderr.write('\n');
 }

+if(sys.stdin.isatty()){
 try{
    import readline;
    import atexit;
@@ -24,6 +25,7 @@
 }catch(Exception e){
    sys.stderr.write(str(e) + '\n');
 }
+}

 escape_data = false;

@@ -183,8 +185,8 @@
    resp = link.request('auth', [password]);    
 }

-welcome();
 if(sys.stdin.isatty()){
+   welcome();
    util.show_version(link);
 }

@@ -235,9 +237,13 @@

 while(true){
    line = '';
-   c = sprintf('ssdb %s:%s> ', host, str(port));
+   if(sys.stdin.isatty()){
+       c = sprintf('ssdb %s:%s> ', host, str(port));
+   }else{
+       c = '';
+   }
    b = sys.stdout;
-   sys.stdout = sys.stderr;
+   sys.stdout = sys.stderr;
    try{
        line = raw_input(c);
    }catch(Exception e){
@@ -409,7 +415,9 @@
                break;
        }
        if(skip){
-           sys.stderr.write(sprintf('(%.3f sec)\n', time_consume));
+           if(sys.stdin.isatty()){
+               sys.stderr.write(sprintf('(%.3f sec)\n', time_consume));
+           }
            continue;
        }
ideawu commented 4 years ago

or, you can ignore output from stderr

echo "get a" | ./tools/ssdb-cli 2>/dev/null
ghen2 commented 4 years ago

That's the point, I don't want to simply discard stderr, or I will not see real errors either (like connection refused etc).

alanhamlett commented 3 years ago

I'd also like this feature. One way to do it is a "headless" mode, where you can pass a command without needing stdin nor shell. When a command is present, just print any output from that command and exit without ever opening the cli's shell and accompanying noise.

Currently I do stuff like this from cron, but would be nice to monitor for connection errors easier:

newline=$'\n' && ssdb-cli <<< "compact${newline}q"