I have a Python program, A.py, that creates binary data upon completion. To help users analyze the output, I want to add a small script, B.sh, to the output directory that fires up a Python console and executes some commands, C, that load the data and prepare them such that a user sees what is available. After executing C, the script B.sh should keep the Python console open.
First attempt at B.sh:
I figured out that
#!/bin/sh
xterm -e python
opens a Python console and keeps it open but doesn't execute anything within that console.
Second attempt at B.sh:
I figured out that
#!/bin/sh
xterm -e python -i C.py
executes C.py (I'd prefer not to have to write an additional file for the startup commands, but I could live with that) and keeps the window open, but doesn't show what was done. More specifically, the user would be presented with the outputs of C, but not the command that were used to achieve the outputs.
Instead,I'd like the user to be presented with a console like this:
>>> [info,results] = my_package.load(<tag>)
>>> my_package.plot(results)
>>> print(info)
<output>
>>> my_package.analyze(results)
<output>
>>>
Save this in a file called demo.tcl
#!/usr/local/bin/expect -f
# Spawn Python and await prompt
spawn /usr/local/bin/python3
expect ">>>"
# Send Python statement and await prompt
send "print('Hello world!')\n"
expect ">>>"
# Pass control to user so he can interact with Python
interact
Then make it executable with:
chmod +x demo.tcl
And run with:
xterm -e ./demo.tcl
In the picture, you can see I went on after the "Hello world" to print the system version info.
Your paths for Python and expect may be different, so check and alter to suit.
For anyone who happens to be using macOS (a.k.a. OSX), you can install expect with homebrew as follows:
brew install expect
And, since Macs don't ship with X11 any more, rather than install XQuartz and run xterm, you can start a new Terminal and run the Python in there quite simply with:
open -a Terminal.app demo.tcl
As suggested by user #pask I simply printed the commands before executing them.
Furthermore, I added a -c switch to be able to put the Python commands directly in B.sh instead of having to write a file C.py
Here is the B.sh I am using now:
#!/bin/sh
xterm -e python -i -c "print('>>> import my_package');import my_package;print('>>> [info,results] = my_package.load()');[info,results] = my_package.load()"
Related
I am attempting to get a subprocess call that will open a gnome-terminal and in that terminal enter python then execute some python commands and imports without the user needing to type them out.
I'm working on on some automated terminal opening code that will open a gnome-terminal window using subprocess.call (Open new gnome-terminal and run command) also (Python syntax to open gnome-terminal and execute multiple commands)
My end goal is to open up a gnome-terminal window and with the same script that opened the gnome-terminal, enter the command to use python. And then in python import a package and run it.
My current usage is:
subprocess.call(['gnome-terminal', '-e', "python client.py"])
However what Im trying to get to is an importable package that I can open several gnome terminal windows for that will call different objects from a pypi package effectively doing the same thing that call client.py would do with the files. This doesnt work with packages installed in pip however.
What I want to do is something along the lines of:
subprocess.call(['gnome-terminal', '-e', "python && import <package> && c = <package>.obj.func()"])
So that a terminal would open and enter python, import the package I want, then call something from it, but all as instructed by a python file
This doesnt appear to work as multiline scripting works for stuff like bash scripting but doesnt seem to work when trying to enter commands after python has been entered.
Any advice would be greatly appreciated
I don't have Gnome Terminal installed, but if you can get that to start Python correctly, then you can use Python's -i flag to run a set of commands or a script.
The two usages are as follows:
python -i path/to/my/script run the script then enter the interpreter
python -i -c "# Some Python commands" run the command(s) then enter the interpreter
For example:
$ python -i -c "import this"
[poetry]
>>>
# Ready for input!
I want to open a new terminal through python. In that newly spawned terminal I want to execute commands. I've checked multiple posts which are suggested through similar questions but I couldn't find the answer.
I've tried this:
import os
os.system("gnome-terminal -e 'cd /home/john/Documents; echo 'writing to file' > testfile.txt'")
The new terminal spawns but the commands don't get executed in the new terminal.
❯ python3 TestOpenTerminal.py
# Option “-e” is deprecated and might be removed in a later version of gnome-terminal.
# Use “-- ” to terminate the options and put the command line to execute after it.
# Error: Failed to execute child process “cd” (No such file or directory)
How can I do this? Thx
The cd command don't work with gnome-terminal command, you need to use the option --working-directory=/path/to/dir.
The -e option is deprecated, you need to use -- followed by the command, like gnome-terminal -- 'command'.
To manipulate files the only way I could make work is using bash and option -c before the command.
So the command you want to do is:
gnome-terminal --working-directory=/home/john/Documents -- bash -c "echo 'writing to file' > testfile.txt"
I really recommend you to use the fabric library to use with terminal commands, it works with all systems and returns the output to you.
I don't know if you really want to open a terminal, but you could just open the file through python and write with it. Try to use the open() and write() functions.
Look closely at your command. Your opening single quote is closed by the single quotes around 'writing to file' and that causes a mess.
os.system("gnome-terminal -e 'cd /home/john/Documents; echo 'writing to file' > testfile.txt'")
Also, the default behavior of gnome-terminal is to close when complete. You can keep it open by editing the profile as follows...
In gnome-terminal, go to Edit -> Profile Preferences -> Title. Click the Command tab. Select Hold the terminal from the drop-down menu labelled When command exits. You should create a new profile for that and execute with
gnome-terminal --window-with-profile=NAMEOFTHEPROFILE -e command
How to get an sh script for starting a new terminal, execute a python script and keep it running? The python script is supposed to run continuously in a perpetual loop, spitting out results as they pop in. Whenever trying with sh-script for gnome-terminal just getting: child process exited normally with status 2
Manually it would just be: python home/ubuntu/pyscript.py
Could someone give an idea how to do this?
I have a list of scripts to run, so resorting to the manual solution is tedious.
You can use gnome-terminal with the -x flag.
Suppose you have a spam.py script; then the following command will spawn a new terminal, run spam.py in it, and close the terminal once the script has ended.
gnome-terminal -x python spam.py
Try with this script:
# spam.py
import time
for _ in range(5):
print("eggs")
time.sleep(1)
Then the previous command will spawn a terminal, that will be printed eggs five times, and then will be closed.
If you want to leave the terminal open with the Python interpret still running after the script ended, then Python's -i flag (doc then CTRL+F -> -i) is what you want:
gnome-terminal -x python -i spam.py
To run the Python script in a new instance of your favourite terminal, write:
x-terminal-emulator -e python -i home/ubuntu/pyscript.py
This will start the Python script and run it until it ends, then display a Python prompt to stop the terminal emulator from closing.
This will work with x-terminal-emulator substituted with any of the many, many terminals installed on my computer, so will work with little modification across all POSIX-compatible systems with the standard terminals installed. This won't work on a Mac, however. For a properly cross-platform Python implementation of something slightly different, see here. Most of the techniques should be transferable.
To run the Python script in the same terminal whilst carrying on with the rest of the shell script, write:
python home/ubuntu/pyscript.py &
Note the &, which runs the program as a new process (but still connects the output to the virtual terminal).
I am working with Ubuntu 16.04 on an NVIDIA TX2 system and have a shell script launcher.sh containing the following commands:
#!/bin/sh
cd /home/nvidia
sudo python test.py >> /home/nvidia/test_output.txt,
basically implying to store the output of test.py in test_output.txt.
The test.pyhas one line: print "Testing startup script!"
I want this script (and more complicated scripts later on) to run automatically when the system boots up. To this end, I added it to the Startup Applications with the command /home/nvidia/launcher.sh and rebooted the system. The file test_output.txt is indeed created but there is no output written in it. I tested the script from the terminal and it works fine.
How do I make this to work from Startup Applications?
Init scripts often don't have the complete environment initialized, e. g. PATH. In order to be executed you better provide the complete paths to commands.
On the other hand sudo is unnecessary here, as you obviously don't do anything that needs root permissions. If you need it, be aware that sudo is asking interactively for a password, which stalls the execution of the script, if the command you try to execute with it isn't explictely permitted in /etc/sudoers.
Provided test.py is located in /home/nvidia, and python in /usr/bin, the script should read
#!/bin/sh
cd /home/nvidia
/usr/bin/python test.py >> test_output.txt
And if you want to add error output to the outfile, which may be useful for debugging, make the last line
/usr/bin/python test.py >> test_output.txt 2&>1
or for a separate error log
/usr/bin/python test.py >> test_output.txt 2> test_error.log
This is probably a very simple question, but I just can't figure it out. I've coded a Python GUI application (uses PyQT), and all I want to do is to launch it with an executable script. I'm still debugging the application, so it'd be nice if the terminal stays open to see any errors/print statements/exceptions thrown.
This is what I've got in my script:
#!/bin/sh
x-terminal-emulator -e cd dirname && python GUIapp.py
It successfully runs the Python application, but once the application loads, the terminal automatically closes. The application continues to run after the terminal closes.
I know I can open a terminal and then simply type in "cd dirname && python GUIapp.py", but I'm lazy.
What am I missing here?
Use --hold or --noclose option. They have the same function with different name.
So change script to
#!/bin/sh
x-terminal-emulator --noclose -e cd dirname && python GUIapp.py
If you are looking for a command option, always check --help. In this case it gives you the needed information.
user#host:~/projects$ x-terminal-emulator --help
Usage: x-terminal-emulator [Qt-options] [KDE-options] [options] [args]
Terminal emulator
Generic options:
[...]
Options:
[...]
--hold, --noclose Do not close the initial session automatically when it ends.
[...]