您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

仅运行一个python程序(如Firefox)?

仅运行一个python程序(如Firefox)?

Firefox的工作方式是:第一个实例创建一个套接文件(或Windows上的命名管道)。这既是Firefox的下一个实例检测并与第一个实例通信,又是在死之前将URL转发给它的一种方式。套接文件或命名管道只能从本地系统上运行的进程访问(就像文件一样),没有网络客户端可以访问它。由于它们是文件,因此防火墙也不会阻止它们(就像在文件上写入文件一样)。

这是一个天真的实现,以说明我的观点。首次启动时,将lock.sock创建套接文件。脚本的进一步启动将检测到锁并将URL发送给它:

import socket
import os

SOCKET_FILENAME = 'lock.sock'

def server():
    print 'I\'m the server, creating the socket'
    s = socket.socket(socket.AF_UNIX, socket.soCK_DGRAM)
    s.bind(SOCKET_FILENAME)

    try:
        while True:
            print 'Got a URL: %s' % s.recv(65536)
    except KeyboardInterrupt, exc:
        print 'Quitting, removing the socket file'
        s.close
        os.remove(SOCKET_FILENAME)

def client():
    print 'I\'m the client, opening the socket'
    s = socket.socket(socket.AF_UNIX, socket.soCK_DGRAM)
    s.connect(SOCKET_FILENAME)
    s.send('http://stackoverflow.com')
    s.close()

def main():
    if os.path.exists(SOCKET_FILENAME):
        try:
            client()
        except (socket.error):
            print "Bad socket file, program closed unexpectedly?"
            os.remove(SOCKET_FILENAME)
            server()
    else:
        server()

main()

您应该实现一个适当的协议(例如,发送适当的数据报而不是硬编码长度),也许使用SocketServer,但这超出了这个问题。在Python的Socket编程HOWTO也可能帮助你。我没有可用的Windows计算机,因此我无法确认它是否可以在该平台上运行。

python 2022/1/1 18:51:23 有429人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶