英文:
Starting a shell script in a new Terminal using python and get exit code
问题
I'm currently trying to run a shell script via python in a new terminal. So far it is working right now, my issue now is that I also need the exit code of that shell script. Depending on successful execution or not the script returns different exit codes and I need to get them so I can continue working with them in python. My code looks like that right now:
process = subprocess.Popen(['gnome-terminal', '-x', './myscript.sh'])
text = process.communicate()[0]
exit_code = process.returncode
print(text, exit_code)
I probably also need a wait function, because the script needs few seconds to finish execution. Does anyone know how I can do all that?
英文:
I'm currently trying to run a shell script via python in a new terminal. So far it is working right now, my issue now is that I also need the exit code of that shell script. Depending on successful execution or not the script returns different exit codes and I need to get them so I can continue working with them in python. My code looks like that right now:
process = subprocess.Popen(['gnome-terminal', '-x', './myscript.sh'])
text = process.communicate()[0]
exit_code = process.returncode
print(text, exit_code)
I probably also need a wait function, because the script needs few seconds to finish execution. Does anyone know how I can do all that?
答案1
得分: 1
如@tjm3772在评论中提到的,subprocess.run 可能是你想要的。例如:
import subprocess
process = subprocess.run(['bash', './bash_script.sh'], capture_output=True, timeout=120)
text = process.stdout
exit_code = process.returncode
print(text, exit_code)
capture_output
和 timeout
都是可选的。timeout
的单位是秒。如你从文档中所见,如果需要的话,还有许多其他选项。
run
返回一个表示已完成进程的 CompletedProcess 对象。因此,在你的Python代码中,无需担心你的shell脚本可能需要多长时间等等。(除非你可能希望像上面提到的那样设置一个timeout
,以应对脚本挂起/运行时间过长的可能情况。)
英文:
As @tjm3772 mentioned in the comments, subprocess.run is probably what you want. e.g.
import subprocess
process = subprocess.run(['bash', './bash_script.sh'], capture_output=True, timeout=120)
text = process.stdout
exit_code = process.returncode
print(text, exit_code)
Both capture_output
and timeout
are optional. timeout
is in seconds. As you'll see from the docs, there are many other options if required.
run
returns a CompletedProcess object representing a process that has finished. So no need to worry about (in your Python code) how long your shell script may take etcetera. (Other than perhaps wanting a timeout
as mentioned above to cover the possible scenario of your script hanging/taking too long.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论