Console in new window - python

I want the commands that run a python file with console
are in an independent window
my code:
def update(self):
self.prombt("sh /usr/script/update.sh")
self.close(None)
def prombt(self, com):
self.session.open(Console,_("sTaRt ShElL cOm: %s") % (com), ["%s" % com])
it's possible?
Tank's

You can realize this using the subprocess module.
import subprocess
subprocess.call(["gnome-terminal", "-x", "sh", "/usr/script/update.sh"])
In this example I used "gnome-terminal" as my terminal emulator. On your system you may not have this emulator and you should replace it with the one you use (e.g. Konsole for KDE).
You must then also find the appropriate parameter (in this case "-x") to execute the command, when opening the emulator.

To accomplish this, you can use either subprocess or os.system().
Whichever one you use, the bash command to do so would be:
gnome-terminal -e sh /usr/script/update.sh
for subprocess:
import subprocess
subprocess.call(["gnome-terminal", "-x", "sh", "/usr/script/update.sh"])
for 'os.system()'
import os
os.system("gnome-terminal -e "sh /usr/script/update.sh"")
It is recommended you use subprocess.call() for anything more complex than simple commands as os.system() is outdated.

Related

How to add environment variables to the bash opened by subprocess module?

I need to use the wget in a Python script with the subprocess.call function, but it seems the "wget" command cannot be identified by the bash subprocess opened by python.
I have added the environment variable (the path where wget is):
export PATH=/usr/local/bin:$PATH
to the ~/.bashrc file and the ~/.bash_profile file on my mac and guaranteed to have sourced them.
And the python script looks like:
import subprocess as sp
cmd = 'wget'
process = sp.Popen(cmd ,stdout=sp.PIPE, stdin=sp.PIPE,
stderr=sp.PIPE, shell=True ,executable='/bin/bash')
(stdoutdata, stderrdata) = process.communicate()
print stdoutdata, stderrdata
The expected output should be like
wget: missing URL
Usage: wget [OPTION]... [URL]...
But the result is always
/bin/bash: wget: command not found
Interestingly I can get the help output if I type in wget directly in a bash terminal, but it never works in the python script. How could it be?
PS:
If I change the command to
cmd = '/usr/local/bin/wget'
then it works. So I am sure I got wget installed.
You can pass an env= argument to the subprocess functions.
import os
myenv = os.environ.copy
myenv['PATH'] = '/usr/local/bin:' + myenv['PATH']
subprocess.run(..., env=myenv)
However, you probably want to avoid running a shell at all, and instead augment the PATH that Python uses to find the binary to run in the subprocess call.
import subprocess as sp
import os
os.environ['PATH'] = '/usr/local/bin:' + os.environ['PATH']
cmd = 'wget'
# use run instead of Popen
# don't needlessly use a shell
# and thus put [cmd] as a list
process = sp.run([cmd], stdout=sp.PIPE, stdin=sp.PIPE,
stderr=sp.PIPE,
universal_newlines=True)
print(process.stdout, process.stderr)
Running Bash commands in Python explains the changes I made in more detail.
However, there is no good reason to use an external utility for this; Python requests does pretty everything wget does, often more naturally and with more control over what exactly it does.

difference between terminal execution and popen

Typing the command in my ubuntu terminal recognizes the parameter t in my command:
/home/daniel/Downloads/SALOME-7.6.0-UB14.04/salome start -t
What is the difference when starting the same process in python via Popen?
command ='/home/daniel/Downloads/SALOME-7.6.0-UB14.04/salome'
commandargs= 'start -t'
import subprocess
subprocess.Popen([command, commandargs], shell=True).wait()
My parameter stands for terminal mode but running my application (salome) via python Popen opens the GUI.
See: https://docs.python.org/3.5/library/subprocess.html#subprocess.Popen
args should be a sequence of program arguments or else a single string.
See also: https://stackoverflow.com/a/11309864/2776376
subprocess.Popen([command, commandargs.split(' ')], shell=True).wait()
alternatively you could do, although less recommended:
subprocess.Popen(command + commandargs, shell=True).wait()
should do the trick

Opening a terminal running the same program in Python

I am familiar with how to open a terminal from Python (os.system("gnome-terminal -e 'bash -c \"exec bash\"'")), but is there a way to open another terminal running the same program that opened the new terminal?
For instance, if I was running a program called foo.py and it opened another terminal, the new terminal would also be running foo.py.
See this question, it's pretty close. You want to add sys.argv as a parameter, though:
import sys
import subprocess
cmd = 'xterm -hold -e ./{0}'.format(' '.join(sys.argv))
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Be sure you somehow check how many processes/terminals you run already, otherwise it will hang your machine in a matter of seconds.

Calling alias Command from python script

I need to run an OpenFOAM command by automatized python script.
My python code contains the lines
subprocess.Popen(['OF23'], shell=True)
subprocess.Popen(['for i in *; do surfaceConvert $i file_path/$i.stlb; done', shell=True)
where OF23 is a shell command is defined in alias as
alias OF23='export PATH=/usr/lib64/openmpi/bin/:$PATH;export LD_LIBRARY_PATH=/usr/lib64/openmpi/lib/:$LD_LIBRARY_PATH;source /opt/OpenFOAM/OpenFOAM-2.3.x/etc/bashrc'
This script runs the OpenFOAM command in terminal and the file_path defines the stl files which are converted to binary format
But when I run the script, I am getting 'OF23' is not defined.
How do I make my script to run the alias command and also perform the next OpenFOAM file conversion command
That's not going to work, even once you've resolved the alias problem. Each Python subprocess.Popen is run in a separate subshell, so the effects of executing OF23 won't persist to the second subprocess.Popen.
Here's a brief demo:
import subprocess
subprocess.Popen('export ATEST="Hello";echo "1 $ATEST"', shell=True)
subprocess.Popen('echo "2 $ATEST"', shell=True)
output
1 Hello
2
So whether you use the alias, or just execute the aliased commands directly, you'll need to combine your commands into one subprocess.Popen call.
Eg:
subprocess.Popen('''export PATH=/usr/lib64/openmpi/bin/:$PATH;
export LD_LIBRARY_PATH=/usr/lib64/openmpi/lib/:$LD_LIBRARY_PATH;
source /opt/OpenFOAM/OpenFOAM-2.3.x/etc/bashrc;
for i in *;
do surfaceConvert $i file_path/$i.stlb;
done''', shell=True)
I've used a triple-quoted string so I can insert linebreaks, to make the shell commands easier to read.
Obviously, I can't test that exact command sequence on my machine, but it should work.
You need to issue shopt -s expand_aliases to activate alias expansion. From bash(1):
Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt [...]
If that does not help, check if the shell executed from your Python program is actually Bash (e.g. by echoing $BASH).
If your command may use bash-isms then you could pass executable parameter otherwise /bin/sh is used. To expand aliases, you could use #Michael Jaros' suggestion:
#!/usr/bin/env python
import subprocess
subprocess.check_call("""
shopt -s expand_aliases
OF23
for i in *; do surfaceConvert $i file_path/$i.stlb; done
"""], shell=True, executable='/bin/bash')
If you already have a working bash-script then just call it as is.
Though to make it more robust and maintainable, you could convert to Python parts that provide the most benefit e.g., here's how you could emulate the for-loop:
#!/usr/bin/env python
import subprocess
for entry in os.listdir():
subprocess.check_call(['/path/to/surfaceConvert', entry,
'file_path/{entry}.stlb'.format(entry)])
It allows filenames to contain shell meta-characters such as spaces.
To configure the environment for a child process, you could use Popen's env parameter e.g., env=dict(os.environ, ENVVAR='value').
It is possible to emulate source bash command in Python but you should probably leave the parts that depend on it in bash-script.

Python/CMD command

So I am running a command in my python py file
myNewShell = os.system('start "%s" /d "%s" cmd /f:on /t:0A /k "W:\\Desktop\\alias.bat"' % (myShot, myWorkDir))
This opens up a shell
How exactly would I input something into this shell directly from my python script, thus bypassing your actual cmd.exe. I have a bunch of DOSKEYs set up, such as maya which opens up the maya program. How would I add a line of code to my python script, so that it loads the shell with those aliases and inputs my command directly
Take a look at the powerful and useful subprocess module
You can then do code like this
import subprocess
pro = subprocess.Popen("cmd", stdout=subprocess.PIPE, stdin=subprocess.PIPE)
pro.stdin.write("mybat.bat\n")
pro.stdin.write("myother.bat\n")
pro.stdin.write("start mysillyprogram\n")
pro.stdin.flush()
pro.terminate() # kill the parent

Categories