在Python中启动一个新终端并执行shell脚本,并获取退出代码。

huangapple go评论65阅读模式
英文:

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_outputtimeout 都是可选的。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.)

huangapple
  • 本文由 发表于 2023年3月7日 01:16:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定