Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
727 views
in Technique[技术] by (71.8m points)

bash - Using Python to open a shell environment, run a command and exit environment

I'm trying to automate a process using python. If I am just in the terminal the workflow looks like:

user:> . /path/to/env1.sh
user:> python something.py
user:> exit
user:> . /path/to/env2.sh
user:> python something2.py
user:> exit 

etc for a few more steps. Each env.sh spawns a new script with a whole slew of environment variables and whatnot set within the current directory. I'm pretty sure I need to use subprocess, but I'm not exactly sure how to go about it. Ideally the workflow would go: open new shell --> run some commands --> exit shell --> repeat as necessary.

EDIT: It seems some clarification is needed. I understand how to use subprocess.Popen() and subprocess.call() to call things from within the shell that the Python script was called from. This is not what I need. When one calls env.sh it sets a whole ton of environment variables and a few other pertinent things and then drops you into a shell to run commands. It is important to note env.sh does not terminate until one types exit after running desired commands. Using subprocess.call("./env.sh", shell = True) opens the shell and stops there. It is just like entering the command ./env.sh except that when one issues the exit command, the rest of the python script. So:

subprocess.call(". /path/to/env.sh", shell = True)
subprocess.call("python something.py", shell = True)

Does NOT do what I need it to do, nor does:

p = subprocess.Popen(". /path/to/env.sh", shell = True)
subprocess.call("python something.py", shell = True)
p.kill()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use subprocess:

>>> import subprocess
>>> subprocess.call('python something.py', shell = True)

Or you can use os:

>>> import os
>>> os.system('python something.py')

Here is an example (turn on your speakers):

>>> import os
>>> os.system('say Hello')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...