简体   繁体   English

如何在 EC2 服务器上连续运行 Python 脚本?

[英]How to continuously run a Python script on an EC2 server?

I've setup an Amazon EC2 server.我已经设置了一个 Amazon EC2 服务器。 I have a Python script that is supposed to download large amounts of data from the web onto the server.我有一个 Python 脚本,它应该从 web 下载大量数据到服务器上。 I can run the script from the terminal through ssh , however very often I loose the ssh connection.我可以通过ssh从终端运行脚本,但是我经常会松开ssh连接。 When I loose the connection, the script stops.当我失去连接时,脚本停止。

Is there a method where I tell the script to run from terminal and when I disconnect, the script is still running on the server?有没有一种方法可以让脚本从终端运行,当我断开连接时,脚本仍在服务器上运行?

You have a few options.你有几个选择。

  • You can add your script to cron to be run regularly.您可以将脚本添加到cron以定期运行。
  • You can run your script manually, and detach+background it using nohup .您可以手动运行脚本,并使用nohup将其分离+背景。
  • You can run a tool such as GNU Screen, and detach your terminal and log out, only to continue where you left off later.您可以运行诸如 GNU Screen 之类的工具,然后分离您的终端并注销,然后再从您离开的地方继续。 I use this a lot.我经常使用这个。
    • For example:例如:
      1. Log in to your machine, run: screen .登录到您的机器,运行: screen
      2. Start your script and either just close your terminal or properly detach your session with: Ctrl+A, D, D.启动您的脚本,然后关闭您的终端或使用以下命令正确分离您的 session:Ctrl+A、D、D。
      3. Disconnect from your terminal.断开与终端的连接。
      4. Reconnect at some later time, and run screen -rD .稍后重新连接,然后运行screen -rD You should see your stuff just as you left it.你应该看到你的东西,就像你离开它一样。
  • You can also add your script to /etc/rc.d/ to be invoked on book and always be running.您还可以将脚本添加到/etc/rc.d/以在书上调用并始终运行。

You can also use nohup to make your script run in the background or when you have disconnected from your session:您还可以使用nohup使您的脚本在后台运行,或者在您与 session 断开连接时运行:

nohup script.py &

The & at the end of the command explicitly tells nohup to run your script in the background.命令末尾的&明确告诉nohup在后台运行您的脚本。

If it just a utility you run ad-hoc, not a service daemon of some kind, i would just run it in screen .如果它只是您运行临时的实用程序,而不是某种服务守护程序,我会在screen中运行它。 Than you can disconnect if you want and open the terminal back up later... Or reconnect the terminal if you get disconnected.如果您愿意,您可以断开连接并稍后打开终端备份......或者如果您断开连接,请重新连接终端。 It should be in your linux distros package manager.它应该在您的 linux 发行版 package 管理器中。 Just search for screen只搜索screen

http://www.gnu.org/software/screen/ http://www.gnu.org/software/screen/

nohup runs the given command with hangup signals ignored, so that the command can continue running in the background after you log out. nohup在忽略挂断信号的情况下运行给定命令,以便在您注销后该命令可以继续在后台运行。

Syntax:句法:

nohup Command [Arg]...

Example:例子:

nohup example.py
nohup rasa run

Also, you can run scripts continuously using the cron command.此外,您可以使用cron命令连续运行脚本。

For more:更多:

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM