Quick Way to Leverage Python in the Console

Leverage a heredoc to run code in an interpreter such as python or node.

Tools like sed and awk are tried and true. Sometimes though, I just want to accomplish some string manuipulation or other task using Python or Node.js without having to open a text editor such as Vim, write a script, and then execute it.

Resources

Title case the string "Squash commits into one with Git"

In [135]:
read -d -r CODE <<'EOL'
import sys


print(sys.argv) # Demo to show how args can be passed.
print(sys.stdin.read().title())

EOL

echo Squash commits into one with Git | python -c "$CODE" args > $s # $s is a path to a scratch file
In [136]:
echo $(< $s)
['-c', 'args'] Squash Commits Into One With Git

Try to replicate this with node interpreter.

Struggling.

Struggled.

Define a variable with the JS code in it.

In [137]:
read -d -r CODE <<'EOL'


var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function (line) {
  const length = line.length;
  console.log({length, line})
});


EOL

Get expected result by writing a file and then running it with node.

In [138]:
echo "$CODE" > test.js
printf "aa\nbbbb\nxxxxx\n" | node test.js
{ length: 2, line: 'aa' }
{ length: 4, line: 'bbbb' }
{ length: 5, line: 'xxxxx' }

Get expected result by running code that does not evaluate stdin.

In [142]:
read -d -r TESTCODE <<'EOL'
console.log('hello, world');
EOL

echo "$TESTCODE" | node
hello, world

Cannot figure out how to write to stdin of executing code piped into node.

In [143]:
printf "aa\nbbbb\nxxxxx\n" | echo "$CODE" | node

This feels like a hack.

But maybe not. This blog post gives a similar example.

In [147]:
printf "aa\nbbbb\nxxxxx\n" | node --eval "$CODE"
{ length: 2, line: 'aa' }
{ length: 4, line: 'bbbb' }
{ length: 5, line: 'xxxxx' }
In [148]:
printf "aa\nbbbb\nxxxxx\n" | node --print "$CODE"
Interface {
  _sawReturnAt: 0,
  isCompletionEnabled: true,
  _sawKeyPress: false,
  _previousKey: null,
  escapeCodeTimeout: 500,
  _events: [Object: null prototype] {
    close: [Function: bound onceWrapper] {
      listener: [Function: onSelfCloseWithoutTerminal]
    },
    line: [Function]
  },
  _eventsCount: 2,
  _maxListeners: undefined,
  output: WriteStream {
    connecting: false,
    _hadError: false,
    _parent: null,
    _host: null,
    _readableState: ReadableState {
      objectMode: false,
      highWaterMark: 16384,
      buffer: BufferList { head: null, tail: null, length: 0 },
      length: 0,
      pipes: null,
      pipesCount: 0,
      flowing: null,
      ended: false,
      endEmitted: false,
      reading: false,
      sync: true,
      needReadable: false,
      emittedReadable: false,
      readableListening: false,
      resumeScheduled: false,
      paused: true,
      emitClose: false,
      autoDestroy: false,
      destroyed: false,
      defaultEncoding: 'utf8',
      awaitDrain: 0,
      readingMore: false,
      decoder: null,
      encoding: null
    },
    readable: false,
    _events: [Object: null prototype] { end: [Function: onReadableStreamEnd] },
    _eventsCount: 1,
    _maxListeners: undefined,
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: false,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      bufferedRequest: null,
      lastBufferedRequest: null,
      pendingcb: 0,
      prefinished: false,
      errorEmitted: false,
      emitClose: false,
      autoDestroy: false,
      bufferedRequestCount: 0,
      corkedRequestsFree: [Object]
    },
    writable: true,
    allowHalfOpen: false,
    _sockname: null,
    _pendingData: null,
    _pendingEncoding: '',
    server: null,
    _server: null,
    columns: 80,
    rows: 24,
    _type: 'tty',
    fd: 1,
    _isStdio: true,
    destroySoon: [Function: destroy],
    _destroy: [Function: dummyDestroy],
    [Symbol(asyncId)]: 3,
    [Symbol(kHandle)]: TTY { [Symbol(owner)]: [Circular] },
    [Symbol(lastWriteQueueSize)]: 0,
    [Symbol(timeout)]: null,
    [Symbol(kBytesRead)]: 0,
    [Symbol(kBytesWritten)]: 0
  },
  input: Socket {
    connecting: false,
    _hadError: false,
    _parent: null,
    _host: null,
    _readableState: ReadableState {
      objectMode: false,
      highWaterMark: 16384,
      buffer: BufferList { head: null, tail: null, length: 0 },
      length: 0,
      pipes: null,
      pipesCount: 0,
      flowing: true,
      ended: false,
      endEmitted: false,
      reading: false,
      sync: true,
      needReadable: false,
      emittedReadable: false,
      readableListening: false,
      resumeScheduled: true,
      paused: false,
      emitClose: false,
      autoDestroy: false,
      destroyed: false,
      defaultEncoding: 'utf8',
      awaitDrain: 0,
      readingMore: false,
      decoder: null,
      encoding: null
    },
    readable: true,
    _events: [Object: null prototype] {
      end: [Array],
      pause: [Function],
      data: [Function: ondata]
    },
    _eventsCount: 3,
    _maxListeners: undefined,
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: true,
      finished: false,
      destroyed: false,
      decodeStrings: false,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      bufferedRequest: null,
      lastBufferedRequest: null,
      pendingcb: 0,
      prefinished: false,
      errorEmitted: false,
      emitClose: false,
      autoDestroy: false,
      bufferedRequestCount: 0,
      corkedRequestsFree: [Object]
    },
    writable: false,
    allowHalfOpen: false,
    _sockname: null,
    _pendingData: null,
    _pendingEncoding: '',
    server: null,
    _server: null,
    fd: 0,
    [Symbol(asyncId)]: 2,
    [Symbol(kHandle)]: Pipe { reading: false, [Symbol(owner)]: [Circular] },
    [Symbol(lastWriteQueueSize)]: 0,
    [Symbol(timeout)]: null,
    [Symbol(kBytesRead)]: 0,
    [Symbol(kBytesWritten)]: 0
  },
  historySize: 30,
  removeHistoryDuplicates: false,
  crlfDelay: 100,
  _prompt: '> ',
  terminal: false,
  _decoder: StringDecoder {
    encoding: 'utf8',
    [Symbol(kNativeDecoder)]: <Buffer 00 00 00 00 00 00 01>
  },
  [Symbol(line object stream)]: undefined
}
{ length: 2, line: 'aa' }
{ length: 4, line: 'bbbb' }
{ length: 5, line: 'xxxxx' }