【问题标题】:How to stop python script using command line如何使用命令行停止 python 脚本
【发布时间】:2018-10-05 12:11:03
【问题描述】:

我有 python 脚本,可以在后台向/从 FTP 服务器下载/上传文件。

run = 1
while run == 1:    
   get_from_ftp(server, login, password)

我想使用命令行运行和停止我的 python 脚本

喜欢:

myprogram.py startmyprogram.py stop

当我运行命令 myprogram.py stop 变量 run 应该得到值 0 并且循环 (while) 应该上传/下载最后一个文件并停止时,这个想法如下。

请建议我如何实现它。

请不要建议使用kill、ps和ctrl+c

【问题讨论】:

  • 更好的解决方案可能是为您的程序创建系统级服务。您使用的是什么操作系统?
  • 您可以从 python 程序发出信号,它们不必是 SIGKILL,而是像 SIGINT (Ctrl+C) 之类的东西,可能会被困在一个整洁的关闭中。 PID 可以由原始文件写入文件以避免使用ps。我不明白你为什么不想使用kill
  • 我不想用kill,因为我怕在大文件下载过程中,下载会中断。但是如果我停止循环,文件将被下载,然后脚本将被关闭。

标签: python background


【解决方案1】:

由于您希望能够通过命令行进行控制,因此一种方法是使用临时“标志”文件,该文件将由myprogram.py start 创建并由myprogram.py stop 删除。关键是,当文件存在时,myprogram.py 将继续运行循环。

    import os
    import sys
    import time
    FLAGFILENAME = 'startstop.file'


    def set_file_flag(startorstop):
        # In this case I am using a simple file, but the flag could be
        # anything else: an entry in a database, a specific time...
        if startorstop:
            with open(FLAGFILENAME, "w") as f:
                f.write('run')
        else:
            if os.path.isfile(FLAGFILENAME):
                os.unlink(FLAGFILENAME)


    def is_flag_set():
        return os.path.isfile(FLAGFILENAME)


    def get_from_ftp(server, login, password):
        print("Still running...")
        time.sleep(1)


    def main():
        if len(sys.argv) < 2:
            print "Usage: <program> start|stop"
            sys.exit()

        start_stop = sys.argv[1]
        if start_stop == 'start':
            print "Starting"
            set_file_flag(True)

        if start_stop == 'stop':
            print "Stopping"
            set_file_flag(False)

        server, login, password = 'a', 'b', 'c'

        while is_flag_set():
            get_from_ftp(server, login, password)
        print "Stopped"


    if __name__ == '__main__':
        main()

您可以想象,旗帜可以是其他任何东西。这非常简单,如果您想要运行两个以上的实例,那么您至少应该为每个实例命名不同的文件(例如,使用 CLI 参数),以便您可以有选择地停止每个实例。

不过,我确实喜欢@cdarke 提出的关于拦截和处理 CTRL+C 的想法,并且该机制与我的方法非常相似,并且适用于单个实例。

【讨论】:

    【解决方案2】:
    while True: 
       run= int(input("press 1 to run/ 0 to stop: "))
       if run == 1:   
            get_from_ftp(server, login, password)
       elif run ==0:
            # what you want to do
    

    如果我理解你的问题可能是这样的

    【讨论】:

      【解决方案3】:

      你可以在下面使用-

      import sys
      import os
      
      text_file = open('Output.txt', 'w')
      text_file.write(sys.argv[1])
      text_file.close()
      
      if sys.argv[1] == "stop":
          sys.exit(0)
      
      run = 1
      while run == 1:
      
      #   Your code   
      
          fw = open('Output.txt', 'r')
          linesw = fw.read().replace('\n', '')
          fw.close()
          if linesw == "stop":
              os.remove('Output.txt')
              break
      sys.exit(0)
      

      我正在使用 Python 3.7.0。 像python myprogram.py startpython myprogram.py stop 一样运行它。

      【讨论】:

        最近更新 更多