Reputation: 7513
I want to create a GUI python script to launch several processes. All of these processes originally were called by setting up a shell with a perl script (start_workspace.perl), and type the executable file name under the shell. inside, start_workspace.perl, it first set some ENV variables, and then call exec(/bin/bash), which launch the shell, so you can type "execfile" under the prompt to launch.
my problem, from my python script, I still want to use this shell (by subprocess.popen("perl start_workspace.perl")), but I do not want to be stopped to manually input "execfile". I want someway that I can specify the "execfile" at step of calling "start_workspace.perl", and the process can completed without any intervention.
something like command redirection. but I do not know if it is possible.
subprocess.popen(("perl start_workspace.perl") < "execfile")
Upvotes: 1
Views: 926
Reputation: 55752
Using the subprocess
module, it could be achieved this way. You can use the stdin stream to write your command to execute once the actual environment has been set.
start_workspace.perl
print "Perl: Setting some env variables\n";
$ENV{"SOME_VAR"} = "some value";
print "Perl: Starting bash\n";
exec('bash');
In python:
import subprocess
p = subprocess.Popen( "perl start_workspace.perl", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
p.stdin.write('echo "Python: $SOME_VAR"\n')
p.stdin.write("make\n")
(stdoutdata, stderrdata) = p.communicate()
print stdoutdata
print stderrdata
Output is
Perl: Setting some env variables
Perl: Starting bash
Python: some value
make: *** No targets specified and no makefile found. Stop.
Upvotes: 1
Reputation: 13832
You are very close. In the subprocess documentation, see:
stdin, stdout and stderr specify the executed programs’ standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With None, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout.
stdin, stderr, and stdout are named parameters for the popen method. You can open the input file and pass its file descriptor as stdin to your new process.
Upvotes: 2