How to correctly emulate terminal in linux/macOS using exex(go)? - go

I need to emulate a terminal in go. I try to do it like this:
lsCmd := exec.Command("bash", "-c", "ls")
lsOut, err := lsCmd.Output()
if err != nil {
panic(err)
}
fmt.Println(string(lsOut))
And it seems to work correctly (the native ubuntu terminal displays a horizontal list, and the result of this function goes vertically).
But if I specifically call the wrong command, for example exec.Command ("bash", "-c", "lss"), I get:
panic: exit status 127
And in the native ubuntu terminal I get the following result:
Command 'lss' not found, did you mean:
and enumeration of commands.
I need to communicate with the native terminal, and get the same thing as the result of the command if I wrote the command in the standard ubuntu terminal.
What is the best way to do this? Maybe the exec library is not suitable for this? All this is necessary for front-end communication with the OS terminal. On a simple html/css/js page, the user enters a command, after go it sends it to the native terminal of the operating system and returns the result to the front-end.
How I can get the same result of executing commands as if I were working in a native terminal?

The problem
But if I specifically call the wrong command, for example exec.Command
("bash", "-c", "lss"), I get:
panic: exit status 127
And in the native ubuntu terminal I get the following result:
Command 'lss' not found, did you mean:
and enumeration of commands.
This has nothing to do with Go, and the problem is actually two-fold:
Ubuntu ships with a special package, command-not-found, which is usually preinstalled, which tries make terminal more friently for mere mortals by employing two techniques:
It tries to suggest corrections for misspellings (your case).
It tries to suggest packages to install when the user tries to execute a program which would have been be available if the user had a specific package installed.
When the command is not found, "plain" (see below) shell fails the attempt by returning a non-zero exit code.
This is absolutely expected and normal.
I mean, panicking on it is absolutely unwise.
There's a historical difference on how a shell is run on a Unix system.
When a user logs into the system (remember that back in the days the concept of the shell was invented you'd be logging in via a hardware computer terminal which was basically what your GNOME Terminal window is but in hardware, and connected over a wire),
the so-called login shell is started.
The primary idea of a logic shell is to provide interactive environment for the user.
But as you surely know, shells are also capable of executing scripts.
When a shell executes a script, it's running in a non-interactive mode.
The modes a Unix shell can work in
Now let's dig deeper into that thing about interactive vs non-interactive shells.
In the interactive mode:
The shell is usually connected to a real terminal (either hadrware or a terminal emulator; your GNOME Terminal window is a terminal emulator).
"Connected" means that the shell's standard I/O streams are connected to the terminal, so that what the shell prints is displayed by the terminal.
It enables certain bells and whistles for the user, usually providind limited means for editing what is being input (bash, for instance, engages GNU readline.
In the non-interactive mode:
The shell's standard I/O streams are connected to some files (or to "nowhere" — like /dev/null).
No bells and whistles are enabled — as there is nobody to make use of them.
GNU bash is able to run in both modes, and which mode it runs in depends
on how it was invoked.
When initializing in different modes, bash reads different initialization scripts, and this explains why the machinery provided by the command-not-found package gets engaged in the interactive mode and does not when bash is run otherwise — like in your invocation from Go.
What do do about the problem
The simplest thing to try is to run bash with the --login command-line option or otherwise make it think it runs as an interactive shell.
This might solve the problem for your case but not necessarily.
The next possible problem is that some programs do really check whether they're running at a terminal — usually these are programs which insist on real interaction with the user, usually for security purposes, and there are programs which simply cannot run when not connected to a real terminal — these are "full-screen" text UI programs such as GNU Midnight Commander, Vim, Emacs, GNU Nano and anything like this.
To solve this problem, the only solution is to run the shell in a pseudo-terminal environment, and that's what #eudore hinted at in their comment.
The github.com/creack/pty might be a package to start looking at; golang.org/x/crypto/ssh also provides some means to wrangle PTYs.

Related

How to save a Python 2 idle/shell/command prompt interactive session on Windows?

I run calculations on Windows for hours and would like to have the calculation report/log inside the interactive IDLE/shell window be saved to a file at the end by a command.
Would be nice to exit() and close the window too.
As much as I like Linux, this is an Unattended Windows machine, hence, some modules/commands are not available, sadly, and the ability to install other software is limited.
The fact that the developers did not think of a command to save the transactions within the IDLE/shell is surprising.
I know in some environments you can direct the output of a job, like a report to another text file by using the key -o, --o, --output, > to a text file. Surprisingly Python does not support anything like that!
Any help would be appreciated
Thanks
Windows Command Prompt supports stdout redirection and probably stderr redirection. I just tested python -c "print(test)" > F:/dev/tem/out.txt and the print out went to out.txt. Replace -c "print('test') with script.py and the same should happen. Piping stdout of one program to stdin of another might work. You might be able to chain programs with a .bat file. PowerShell likely is more powerful and flexible, but I have never used it.
I am not completely clear on what you are asking, but I hope the following answers your questions.
Python runs in 2 modes: batch and interactive. Interactive mode is intended for ephermeral interaction with a human. Batch mode is for unattended computation, with occasional screen messages, but with most results sent to a file other than the screen. Both modes are combined when you run python -i xyz.py. The file is first run in batch mode, and then Python shifts to interactive mode.
It sounds like you should be using batch mode rather than either Python's or IDLE's interactive mode. If your code runs from IDLE, you should be able to run it directly with the same python.exe that you used to run IDLE. There are exceptions, of course, if one makes one's code dependent on running within IDLE, but this is unlikely to be an accident or to be needed for unattended running.
The IDLE Shell simulates interactive Python. When a file is run from an editor window, IDLE simulates python -i file-being-edited.py, with screen output going to Shell. In either case, an interactive user can save the contents of Shell with the File => Save As menu command. So there is such a command. There are also close window and exit commands and shortcuts.
In IDLE's intended use, as an interactive python learning and program development environment, there is no need from for a program to issue these commands. To save data in a file, a program can open a file and write data directly.
Try to see if you can install Jupyter Notebook (not separate software, but just a python module)
pip install jupyter
Jupyter notebook is highly helpful for saving and sharing your code. It can be used as both a shell and as a script editor.

Custom console using git bash

I understand that console applications using git bash invoke sh.exe but I wonder how they continue to use sh.
I see on console apps often you do a sh.exe --login. I would guess this creates a session somewhere and I would presume that the console application would execute commands against it somehow?
Essentially I switched from UNIX to Windows. I have tried a lot of console apps (best being console2 and just git-bash) but they still do not work for me well.
Ia m annoyed enough that I fancy trying to programming a simple shell in Java. (I am a Java developer by trade.)
Any help would be great thanks to understand this, looking but searchs with console or git-bash in google generate so much random noise.
If you are using one of the various Unix shells ported to Windows, you should be aware that most of these shells use some heuristic to make Windows look like Unix, either to build a compatibility layout or for user convenience.
For instance, the git command is probably stored in a git.exe file but your shell scripts imported from your Unix workstation all say git so the shell will lookup git.exe if it does not find git.
Nobe of these heuristics works perfectly, so you have to expect regular inconsistencies and disagreements, especially if your are mixing several Unix ports together.
As for the meaning of --login, it is synonymous to -l and its main effect is to decide which initialization files are read by bash on startup`
-l Make bash act as if it had been invoked as a login shell (see
INVOCATION below).

GoLang - termbox: panic: open /dev/tty: no such device or address

I am coding with Go 1.2 on Ubuntu 12.04 LTS machine - using LiteIDE (very pleased with it).
I downloaded and installed the go termbox package - built the demo keyboard.go - built fine.
But when I run from LiteIDE, I get this panic - same happens with all the termbox demos:
panic: open /dev/tty: no such device or address
Any clues would be helpful....
OK, that's completely reasonable: interactive terminal applications require, well, terminal to be available. Terminals may be real—hardware—or virtual (like Linux virtual terminals you see on a typical x86 box when you hit Ctrl-Alt-F1) or emulated (like those provided by xterm, rxvt, GNOME Terminal and a ton of others).
Contrary to Windows, in which running a program of type "console" forces a console window to be created and an application attached to it, on POSIX systems there's no "types" of applications, and if an aplication wants a real terminal available for its I/O it performs a special check for this, and if that fails, the application signals an error and quits1. Very few folks have access to real hardware terminals these days so most of the time emulation is used, and then we talk about the so-called pseudo terminals. Linux virtual terminals and GUI terminal emulators and terminal console multiplexors like screen and tmux—all of them allocate pseudo terminals for running programs they control.
So basically you have these options:
Find a setting in your IDE which makes it allocate a pseudo-terminal when running your program. Some programs are able to do that by embedding a terminal emulator into their UI or by running it explicitly.
Teach your IDE to run your program in a terminal emulator. Most of them obey the convention established by the venerable xterm and accept the -e <program> command-line option, so instead of
./myprogram
your IDE should run
xterm -e ./myprogram
If you're on a Debian system or its derivative, you might get away with
x-terminal-emulator -e ./myprogram
which is supposed to spawn your preferred terminal emulator program.
Stop running the code in the IDE and do it in a terminal emulator using the regular
go build
./myprogram
workflow.
I've never used LiteIDE so have no immediate experience with how to do that in it—you'll have to do your own research.
1 Some programs may happily work with or without being attached to a terminal, with shells (like bash or zsh) and interpreters (like Tcl or Python) being good examples: when they detect a terminal device available, they go into interactive mode, enable line editing and so on, otherwise they just read the code from their standard input and execute it. Another good example is Git: its high-level programs detect if they're attached to a terminal and if so they might enable colouring of their output and automatically spawn a pager program if their output if about to overflow the single screenful of lines; otherwise they cut the fuss and just dump their output to their standard output stream.

In Bash, how can I tell if I am currently in a terminal

I want to create my own personal logfile that logs not only when I log in and out, but also when I lock/unlock my screen. Kindof like /var/log/wtmp on steroids.
To do this, I decided to run a script when I log into Ubuntu that runs in the background until I quit. My plan to do this is to add the script to .bashrc, using ./startlogging.sh & and in the script I will use trap to catch signals. That's great, except .bashrc gets run every time I open a new terminal, which is not what I want for the logger.
Is there a way to tell in Bash that the current login is a gnome login? Alternatively, is there some sort of .gnomerc I can use to run my script?
Edit: Here is my script:
Edit 2: Removed the script, since it's not related to the question. I will repost my other question, rather than repurpose this one.
Are you looking for a way to detect what type of terminal it is?
Try:
echo $TERM
From Wikipedia:
TERM (Unix-like) - specifies the type of computer terminal or terminal
emulator being used (e.g., vt100 or dumb).
See also: List of Terminal Emulators
for bash use : ~/.bash_logout
that will get executed when you logout, which sounds like what you are trying to do.
Well, for just bash, what you want are .bash_login/.bash_logout in your home directory (rather than .bashrc) These are run whenever a LOGIN shell starts/finishes, which happens any time you log in to a shell (on a tty or console, or via ssh or other network login). These are NOT run for bash processes created to run in terminal windows that you create (as those are not login shells) so won't get run any time you open a new terminal.
The problem is that if you log in with some mechanism that does not involve a terminal (such as gdm running on the console to start a gnome or kde or unity session), then there's no login shell so .bash_login/logout never get run. For that case, the easiest is probably to put something in your .xsessionrc, which will get run every time you start an X session (which happens for any of those GUI environments, regardless of which one you run). Unfortunately, there's no standard script that runs when an X session finishes.

bash script on cygwin - seems to get stuck between consecutive commands.

I am using a bash script to run a number of application (some repeatedly) on a Windows machine through cygwin. The script contains commands to launch those applications, line by line. Most of these applications run for many minutes and many times I have observed that the i+1 th application is not being started even after i th application is completed. In such cases, if I press enter in the cygwin console on which the bash script is running, the next application starts running. Is it because of any issue with bash on cygwin? Or is it an issue with the Windows OS itself? Have any of you observed such an issue with bash + cygwin + Windows?
Thanks.
I think I have seen this before.
Instead of
somecommand
try
somecommand </dev/null
If that doesn't work, try
cmd /c somecommand
Or experiment with other redirections, e.g.
somecommand >/dev/null
Sounds like you may have a problem with your shell script encoding; DOS (and Windows) uses CR+LF line endings, whereas Linux uses LF endings. Try saving the file as LF.
What might also be going on:
When I was running Cygwin on a school laptop, I encountered a dramatic slowing of shell scripts vs. when they were running in a native Linux environment. This was especially apparent when running a configure script from GNU Autotools.
Check your path for slow drives. (From the Cygwin FAQ):
Why is Cygwin suddenly so slow?
If suddenly every command takes a very long time, then something is probably attempting to access a network share. You may have the obsolete //c notation in your PATH or startup files. Using //c means to contact the network server c, which will slow things down tremendously if it does not exist.
You might also want to check whether you have an antivirus program running. Antivirus programs tend to scan every single executable file as it is executed; this can cause problems for even simple shell scripts that run hundreds or even thousands of individual programs before they run their course.
This mailing list post outlines what is needed to pseudo-mount the main /usr/bin directory as cygexec. I'm not sure what that does, but I found it helped.
If you're running a configure script, try the -C option.
Hope this helps!
Occasionally, I'll get this behaviour because I have accidentally deleted the 'she-bang' at the top of the script, that is, deleted the #!/bin/bash on the first line of the script.
It's even more likely for this to happen when a parent shell script calls a child script that has the she-bang missing!
Hope this helps.
A bit of a long shot, but I have seen some similar behaviour previously.
In Windows 2000, if any program running in a command prompt window had some of it's text highlighted by the cursor, it would pause the command running, and you had to press enter or clear the highlighting to get the command prompt to continue executing.
As I said, bit of a long shot, but accidental mouse clicks could be your issue...
Install cygwin with unix style line breaks and forget weird problems like that.
Try saving your script as "the-properly-line-broken-style" for your cygwin. That is, use the style you specified under installation.
Here is some relevant information:
https://stackoverflow.com/a/7048200/657703

Resources