首页 \ 问答 \ 如何在Python中启动后台进程?(How to start a background process in Python?)

如何在Python中启动后台进程?(How to start a background process in Python?)

我试图将一个shell脚本移植到更可读的python版本。 原始shell脚本在后台使用“&”启动多个进程(实用程序,监视器等)。 如何在python中实现同样的效果? 当python脚本完成时,我希望这些进程不会死机。 我相信它与某个守护进程的概念有关,但我无法找到如何轻松地做到这一点。


I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.


原文:https://stackoverflow.com/questions/1196074
更新时间:2023-12-25 09:12

最满意答案

这是一个示例 - 它不完整,但应该让您了解如何将输出多播到多个侦听客户端。 有更好的方法来做到这一点,但我写的类似于你似乎做插槽的方式。 它也缺乏许多地方的错误检查,我把它作为读者的练习。 此代码也已编写,因此可以在Java 1.6或更高版本上使用。

该代码使用Server对象中维护的已连接客户端列表。 当从一个客户端接收输入时,输出被多播到客户端列表中的每个客户端。 通过Client类中的write方法完成写入。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MulticastEchoServer {
    List<Client> clientList = new LinkedList<Client>();
    ExecutorService executor;

    int port = 40480;
    int max = 10;

    public MulticastEchoServer() {
        this.executor = Executors.newFixedThreadPool(max);
    }

    public void writeToAllClients(String string) throws IOException {
        // Multiple threads access this so it must be in synchronized block
        synchronized (this.clientList) {
            Iterator<Client> iter = this.clientList.iterator();
            while (iter.hasNext())
                iter.next().write(string);
        }
    }

    public void addClient(Client client) {
        // Multiple threads access this so it must be in synchronized block
        synchronized (this.clientList) {
            clientList.add(client);
        }
    }

    public void removeClient(Client client) {
        // Multiple threads access this so it must be in synchronized block
        synchronized (this.clientList) {
            clientList.remove(client);
        }
    }

    public void listen() {
        try {
            ServerSocket server = new ServerSocket(port);
            System.out.println("server started and listening for connections");

            while (true) {
                try {
                    Socket socket = server.accept();
                    System.out.print("connection accepted" + "\n");

                    Client newClient = new Client(this, socket);

                    this.addClient(newClient);
                    this.executor.execute(newClient);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new MulticastEchoServer().listen();
    }

    private class Client implements Runnable {

        Socket socket;
        PrintWriter writer;
        BufferedReader reader;
        MulticastEchoServer server;

        public Client(MulticastEchoServer server, Socket socket) throws IOException {
            this.server = server;
            this.socket = socket;
            this.writer = new PrintWriter(this.socket.getOutputStream());
            this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }

        synchronized public void write(String string) throws IOException {
            writer.write(string);
            writer.flush();
        }

        public void close() {
            this.writer.close();
            try {
                this.reader.close();
            } catch (IOException e) {
            }
            try {
                this.socket.close();
            } catch (IOException e) {
            }
        }

        @Override
        public void run() {
            System.out.println("Client Waiting");

            String inString = null;
            try {
                while ((inString = this.reader.readLine()) != null) {
                    this.server.writeToAllClients(inString + "\n");
                    System.out.println(inString);
                }
            } catch (IOException e1) {
            }

            server.removeClient(this);
            this.close();
            System.out.println("Client Closed");
        }
    }

}

This is an example - it is not complete but should give you an idea how you could multicast output to a number of listening clients. There are better ways to do this, but I wrote it similar to how you appeared to be doing the sockets. It also lacks error checking in many places and I have left that as an exercise for the reader. This code was also written so that it can be used on Java 1.6 or higher.

The code uses a list of connected Clients maintained in the Server object. When input is received from one client, the output is multicast to each client in the Client list. Writing is done via a write method in the Client class.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MulticastEchoServer {
    List<Client> clientList = new LinkedList<Client>();
    ExecutorService executor;

    int port = 40480;
    int max = 10;

    public MulticastEchoServer() {
        this.executor = Executors.newFixedThreadPool(max);
    }

    public void writeToAllClients(String string) throws IOException {
        // Multiple threads access this so it must be in synchronized block
        synchronized (this.clientList) {
            Iterator<Client> iter = this.clientList.iterator();
            while (iter.hasNext())
                iter.next().write(string);
        }
    }

    public void addClient(Client client) {
        // Multiple threads access this so it must be in synchronized block
        synchronized (this.clientList) {
            clientList.add(client);
        }
    }

    public void removeClient(Client client) {
        // Multiple threads access this so it must be in synchronized block
        synchronized (this.clientList) {
            clientList.remove(client);
        }
    }

    public void listen() {
        try {
            ServerSocket server = new ServerSocket(port);
            System.out.println("server started and listening for connections");

            while (true) {
                try {
                    Socket socket = server.accept();
                    System.out.print("connection accepted" + "\n");

                    Client newClient = new Client(this, socket);

                    this.addClient(newClient);
                    this.executor.execute(newClient);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new MulticastEchoServer().listen();
    }

    private class Client implements Runnable {

        Socket socket;
        PrintWriter writer;
        BufferedReader reader;
        MulticastEchoServer server;

        public Client(MulticastEchoServer server, Socket socket) throws IOException {
            this.server = server;
            this.socket = socket;
            this.writer = new PrintWriter(this.socket.getOutputStream());
            this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }

        synchronized public void write(String string) throws IOException {
            writer.write(string);
            writer.flush();
        }

        public void close() {
            this.writer.close();
            try {
                this.reader.close();
            } catch (IOException e) {
            }
            try {
                this.socket.close();
            } catch (IOException e) {
            }
        }

        @Override
        public void run() {
            System.out.println("Client Waiting");

            String inString = null;
            try {
                while ((inString = this.reader.readLine()) != null) {
                    this.server.writeToAllClients(inString + "\n");
                    System.out.println(inString);
                }
            } catch (IOException e1) {
            }

            server.removeClient(this);
            this.close();
            System.out.println("Client Closed");
        }
    }

}

相关问答

更多
  • 这是一个示例 - 它不完整,但应该让您了解如何将输出多播到多个侦听客户端。 有更好的方法来做到这一点,但我写的类似于你似乎做插槽的方式。 它也缺乏许多地方的错误检查,我把它作为读者的练习。 此代码也已编写,因此可以在Java 1.6或更高版本上使用。 该代码使用Server对象中维护的已连接客户端列表。 当从一个客户端接收输入时,输出被多播到客户端列表中的每个客户端。 通过Client类中的write方法完成写入。 import java.io.BufferedReader; import java.io. ...
  • 如果你在谈论HTTP,简单的答案是GAE目前不支持它。 我想你所问的有时被称为BOSH 。 一旦WebSockets变得更加普遍,它们将成为这个问题的绝佳解决方案。 同时你可能想看看XMPP 。 使用XMPP可以避免轮询。 Google已经发布了一个Channel API (尚未发布),它基本上可以为您提供与websockets相同的功能。 If you are talking about HTTP, the short answer is that GAE does not currently suppo ...
  • UDP多播系统可以为此工作,但您自己也会变得复杂(因为您必须担心自己的同步和故障检测/纠正以及节点进出组)。 有各种中间件解决方案,包括分布式缓存,已经很好地解决了这个问题。 看看Infinispan。 如果这个级别太高而您只想要一个较低级别的解决方案,请尝试使用JGroups。 我只列出那些因为我知道它们快速可用,但还有很多其他的。 A UDP multicast system would work for this but will get complicated for you to do yours ...
  • PrintWriter是缓冲的。 如果您希望立即读取,则需要在每条消息后flush() 。 您的读取循环不正确: public void run() { while (true) { try { if (input.ready()) { String message = input.readLine(); print(message); } } catch ...
  • 使用并发hashmap并在其中维护您的客户端列表。 并发hashmap是安全的,您不需要在添加/迭代/删除时使用同步 // Create and main list of active clients based on their host name / ip address ConcurrentHashMap activeClients = new ConcurrentHashMap(); // message received activ ...
  • read只阻止不发送数据的客户端的线程; 所以你理论上可以使用刚刚发送数据的客户端线程write另一个。 另一种方法可能是使客户端套接字无阻塞,如果流中没有数据,则会导致读取立即返回(有错误)。 然而,这是非常耗费处理器的,因为两个套接字都在不断地被探测数据,并且(几乎总是)不返回。 我要查看的地方的最终建议是在select函数中,该函数可用于检查一组文件描述符并阻塞,直到它们中的任何一个在流中有数据为止; 此外,它可以传递超时(阻止多长时间的上限)。 算法的草图可能是: 选择(客户端套接字,100毫秒) ...
  • 我建议让每个客户端建立到服务器的套接字连接。 每个客户端都可以运行一个线程,该线程尝试从套接字进行阻塞读取(将其置于后台线程中),该线程在套接字可用时从套接字中提取信息。 然后,每当服务器写入该套接字时,客户端应立即获取它。 客户端的连接应该是read_until imho的子类,因为它提供了一个方便的read_until方法。 这样的事情可能是: class RPCConnection(object, Telnet): def __init__(self, host = 'localhost', po ...
  • 由于没有答案,我将结束这个问题。 似乎由于Lidgren的某些限制,它只能接收用Lidgren客户端编写的消息。 As there has been no answer, I will close this question. It seems that due to some limitation of Lidgren, it can only receive messages that were written in Lidgren clients.
  • 如果您通过TCP / IP套接字发送数据,则没有“消息”。 您发送和接收的是字节流。 如果你问是否可以发送一个N字节的块,并让接收器在一次读取调用中得到正好N个字节,那么答案就是不能保证会发生。 但是,TCP / IP堆栈正在“分解”“消息”。 不是NIO。 不是Java。 通过TCP / IP连接发送的数据最终被分解为网络数据包以进行传输。 这通常基于原始写请求大小擦除任何“消息”结构。 如果要在TCP / IP字节流的顶部建立可靠的消息结构,则需要在流本身中对其进行编码。 例如,使用“消息结束”标记或为 ...
  • Java中的类应该以大写字母开头。 例如: ServerGUI但不是代码中看到的addClient 。 类表示对象。 或对象的“类”。 例如Car或ServerGUI但不是addClient 。 什么是new addClient() ? 这真是一个对象吗? 如果可能,变量名称应具有重要名称。 例如Car limousine = new Car(4,Color.Black)而不是addClient ob1 = new addClient("RunServer") 。 ob1是什么意思? 评论是读者的新鲜空气。 ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。