Linux nohup指令实现Python代码挂起在后台

1. 方法nohup

nohup指令,是可以让程序在离线或者登出系统继续执行。

当Linux使用者登出系统时,其执行的每个程序都会收到一个 hangup信号,正常的程序收到信号之后会马上停止执行。

nohup的用法很简单,只需要把执行的程序放在他的参数中,而通常我们会在尾端加上 & 把这个程序放在背景执行:

nohup python *.py &

让代码一直在后台运行。

运行提示:

[1] 8324
[root@server-1 bin]# nohup: ignoring input and appending output to ‘nohup.out’

nohup 在執行程式時,會將所有的輸出訊息導入 nohup.txt 這個文字檔,所以若要觀察程式

### 使用 `nohup` 在 Linux 后台执行多行 Python 脚本或命令 为了确保长时间运行的任务不会因为终端关闭而中断,可以使用 `nohup` 命令来忽略挂起信号并使进程继续在后台运行。对于多行 Python 命令或者复杂的逻辑处理,建议先将这些命令封装到一个单独的 Python 文件中再通过 `nohup` 来调用。 #### 方法一:创建独立的 Python 文件并通过 nohup 执行 假设有一个名为 `multi_commands.py` 的文件包含了所有的 Python 语句: ```python # multi_commands.py import os def main(): print("Starting the first command...") os.system('echo "First Command Output" >> output.txt') print("Executing second command after a delay of 5 seconds.") import time time.sleep(5) os.system('echo "Second Command Output" >> output.txt') if __name__ == "__main__": main() ``` 接着可以在 shell 中利用如下方式启动它,并将其放到后台运行而不受当前会话的影响[^1]: ```bash nohup python multi_commands.py > multi_commands.log 2>&1 & ``` 这条指令做了三件事情: - 运行指定的 Python 程序 (`multi_commands.py`) - 将标准输出重定向至 `multi_commands.log` 文件 (覆盖模式),并将错误信息也追加到同一文件(`> file 2>&1`) - 把整个过程放入后台 (&) #### 方法二:直接在 Shell 中编写多条命令并与 nohup 结合 如果不希望创建额外的 .py 文件,则可以直接在一个复合命令字符串里组合多个操作,并传递给 Python 解释器作为参数。不过这种方法适用于较短小简单的场景: ```bash nohup bash -c 'python -c " print(\"Starting\"); open('output_directly_from_shell.txt', 'w').write('Direct from shell\\n'); import time; time.sleep(3); with open('output_directly_from_shell.txt', 'a') as f: f.write('After sleeping\\n')" > direct_execution.log 2>&1 &' ``` 这种方式下需要注意转义字符以及引号的正确匹配以免引起语法错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rosefunR

你的赞赏是我创作的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值