简体   繁体   English

shell 运行 python 脚本后终端不关闭

[英]Terminal doesn't close after shell runs the python script

I have 2 python scripts sc-1.py and sc-2.py and shell file test.sh我有 2 个 python 脚本sc-1.pysc-2.py以及 shell 文件test.sh

sc-1.py

import time 

print('Script 1 started')
time.sleep(2)
print('Script 1 ended')

sc-2.py

import subprocess

print('Script 2 started')
subprocess.Popen(["sh", "test.sh"], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
print('Script 2 ended')

test.sh

py sc-1.py

It works but there is one problem.它有效,但有一个问题。 The command terminal doesn't end after the script is ended.脚本结束后命令终端不会结束。 在此处输入图像描述

I have to use ctrl + c to end it.我必须使用ctrl + c来结束它。

在此处输入图像描述

You forgot to output a final newline in your Python programs, ie to write你忘了 output 在你的 Python 程序中的最后一个换行符,即写

print("Script 2 ended\n")

BTW, in order to make it work on my Platform (Cygwin, Python 3), I also had to do a shell=False , otherwise it would not have executed the shell script at all;顺便说一句,为了让它在我的平台上工作(Cygwin,Python 3),我还必须执行shell=False ,否则它根本不会执行 shell 脚本; but this doesn't seem to be necessary in your case.但这在您的情况下似乎没有必要。

UPDATE : The "solution" posted here applies only when I am running sc-2.py from a interactive zsh.更新:此处发布的“解决方案”仅适用于我从交互式 zsh 运行 sc-2.py 时。 If I use an interactive bash, I see the same effect as the OP mentions, and adding a \n does not help.如果我使用交互式 bash,我会看到与 OP 提到的相同的效果,并且添加 \n 没有帮助。 However, the script is not hanging.但是,脚本没有挂起。 It is terminated, but it just appears hanging because the shell does not display its prompt.它已终止,但它只是显示为挂起,因为 shell 未显示其提示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在运行后强制挂起或暂停python脚本,以便在完成后不强制关闭? - How to hard suspend or pause a python script after it runs so it doesn’t force close upon completion? Python 脚本在 PyCharm 中无法正确运行,但在终端中运行 - Python script doesn't run correctly in PyCharm but runs in terminal 脚本运行后在MacOsx上关闭Python进程 - Close Python Process on MacOsx after script runs Python脚本在终端中运行,但不作为Apache运行 - Python script runs in terminal but not as Apache 脚本在Python中运行,但不在Python Shell中运行 - Script runs in Python but not in Python shell 在shell中运行python的脚本 - The script which runs python in shell 调用shell脚本后如何以编程方式(python)执行终端命令(控件将在shell脚本下) - how to programmatically(python) execute terminal commands after invoking shell script(control will be under shell script)) Python 脚本在 pycharm 中运行但不在 ubuntu 终端中运行 - Python script runs in pycharm but not in ubuntu terminal Python 脚本在 Thonny 中运行,但在终端中出现错误 - Python script runs in Thonny but Errors in terminal Python脚本在Spyder中完美运行(在Windows上) - 在Linux上不起作用 - Python script runs perfectly in Spyder (on Windows) - Doesn't work on Linux
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM