将命令从命令行发送到Unix中正在运行的Python脚本 [英] Send commands from command line to a running Python script in Unix

查看:179
本文介绍了将命令从命令行发送到Unix中正在运行的Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个脚本,当从其他脚本运行时可以控制。例如我想像这样运行我的脚本:

I want to build a script that can be controlled while running from another scripts. For example I want to run my script like this:

~: Server &

并且可以运行其中一个函数:

and be able to run one of it's functions like:

~: client func1

我发现信号模块有我喜欢的东西,但它的信号是预定义的,我不能发送我自己的信号。

Upon my searches I find signal module that have something like I want, but it's signals are predefined and I can not send signals of my own.

我虽然使用网络框架的客户端/服务器实现,但我认为这太多了我想要我的脚本的能力。

I even though of a client/server implementation using a network framework but I think it's too much for the abilities that I want my script to have.

谢谢大家。

推荐答案

向服务器单向发送命令,使用Python的 Sockets 。代码示例当然是准系统,它们不做错误处理,并且不多次调用 recv 以确保消息完成。这只是为了让你知道处理命令需要几行代码。

If you are only trying to send commands one-directionally to a server, it is easier than you think, using Python's Sockets. The code samples are of course barebones in the sense that they do not do error handling, and do not call recv multiple times to make sure the message is complete. This is just to give you an idea of how few lines of code it takes to process commands.

这里是一个服务器程序,只接收消息并打印到 stdout 。注意,我们使用线程,以便服务器可以一次监听多个客户端。

Here is a server program that simply receives messages and prints to stdout. Note that we use threading so that the server can listen to multiple clients at once.

import socket
from threading import Thread


MAX_LENGTH = 4096

def handle(clientsocket):
  while 1:
    buf = clientsocket.recv(MAX_LENGTH)
    if buf == '': return #client terminated connection
    print buf

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

PORT = 10000
HOST = '127.0.0.1'

serversocket.bind((HOST, PORT))
serversocket.listen(10)

while 1:
    #accept connections from outside
    (clientsocket, address) = serversocket.accept()

    ct = Thread(target=handle, args=(clientsocket,))
    ct.run()

这是一个向其发送命令的客户端程序。

Here is a client program that sends commands to it.

import socket
import sys


HOST = '127.0.0.1'
PORT = 10000
s = socket.socket()
s.connect((HOST, PORT))

while 1:
    msg = raw_input("Command To Send: ")
    if msg == "close":
       s.close()
       sys.exit(0)
    s.send(msg)

这篇关于将命令从命令行发送到Unix中正在运行的Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆