简体   繁体   English

如何使用命令行停止python脚本

[英]How to stop python script using command line

I have python script which download/upload files to/from FTP server in background. 我有python脚本,可在后台将文件下载到FTP服务器或从FTP服务器上载文件。

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

I want to run and stop my python script using command line 我想使用命令行运行和停止我的python脚本

Like: 喜欢:

myprogram.py start and myprogram.py stop myprogram.py startmyprogram.py stop

The idea is folowing when i run command myprogram.py stop variable run should get value 0 and cycle ( while ) should upload/download last file and stop. 当我运行命令myprogram.py stop变量run应该获得值0并循环( while )应该上载/下载最后一个文件并停止时,这个想法如下。

Please suggest how can i realize it. 请提出我如何实现它。

Please don't suggest use kill, ps and ctrl+c 请不要建议使用kill,ps和ctrl + c

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

If I understand your question is could be something like that 如果我了解您的问题可能是这样的话

You can use below - 您可以在下面使用-

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)

I am using Python 3.7.0. 我正在使用Python 3.7.0。 Run it like python myprogram.py start and python myprogram.py stop . python myprogram.py startpython myprogram.py stop一样运行它。

Since you want to be able to control via command line, one way to do this is to use a temporary "flag" file, that will be created by myprogram.py start , and deleted by myprogram.py stop . 由于您希望能够通过命令行进行控制,因此一种方法是使用一个临时的“标志”文件,该文件将由myprogram.py start创建,并由myprogram.py stop删除。 The key is that, while the file exists, myprogram.py will keep running the loop. 关键是,尽管文件存在,但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()

As you can imagine, the flag could be anything else. 可以想象,该标志可以是其他任何东西。 This is very simple, and if you want to have more than two instances running, then you should at least name the files differently per instance (for example, with a CLI parameter) so you can selectively stop each instance. 这非常简单,如果要运行两个以上的实例,则每个实例至少应使用不同的名称命名文件(例如,使用CLI参数),以便可以有选择地停止每个实例。

I do like the idea proposed by @cdarke about intercepting and handling CTRL+C, though, and the mechanism is very similar to my approach, and works well with a single instance. 我确实喜欢@cdarke提出的关于拦截和处理CTRL + C的想法,并且该机制与我的方法非常相似,并且可以在单个实例中很好地工作。

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

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