這個問題是雙重的。Python 3.4 - 如何'連續'運行'另一個腳本python腳本,如何將http get/post傳遞給套接字
所以我需要爲這一切都定義和another.py創建一個套接字服務器上運行的代碼,點擊PyCharm運行工作得很好,但如果你exec()
文件,它只是運行的底部碼。
這裏有一些答案,但它們是相互矛盾的,併爲Python 2
從我可以收集有三種方式:
-Execfile()
,我認爲這是Python的2碼。
-os.system()
(但我已經看到了它可以說,這是不正確的傳遞到OS此)
-而subprocess.Popen
(不確定如何可以用這個)
我需要在後臺運行它,它用於爲整個程序的recv部分創建套接字的線程,並偵聽這些端口,以便我可以將命令輸入到路由器。
這是有問題的完整代碼:
import sys
import socket
import threading
import time
QUIT = False
class ClientThread(threading.Thread): # Class that implements the client threads in this server
def __init__(self, client_sock): # Initialize the object, save the socket that this thread will use.
threading.Thread.__init__(self)
self.client = client_sock
def run(self): # Thread's main loop. Once this function returns, the thread is finished and dies.
global QUIT # Need to declare QUIT as global, since the method can change it
done = False
cmd = self.readline() # Read data from the socket and process it
while not done:
if 'quit' == cmd:
self.writeline('Ok, bye. Server shut down')
QUIT = True
done = True
elif 'bye' == cmd:
self.writeline('Ok, bye. Thread closed')
done = True
else:
self.writeline(self.name)
cmd = self.readline()
self.client.close() # Make sure socket is closed when we're done with it
return
def readline(self): # Helper function, read up to 1024 chars from the socket, and returns them as a string
result = self.client.recv(1024)
if result is not None: # All letters in lower case and without and end of line markers
result = result.strip().lower().decode('ascii')
return result
def writeline(self, text): # Helper func, writes the given string to the socket with and end of line marker at end
self.client.send(text.strip().encode("ascii") + b'\n')
class Server: # Server class. Opens up a socket and listens for incoming connections.
def __init__(self): # Every time a new connection arrives, new thread object is created and
self.sock = None # defers the processing of the connection to it
self.thread_list = []
def run(self): # Server main loop: Creates the server (incoming) socket, listens > creates thread to handle it
all_good = False
try_count = 0 # Attempt to open the socket
while not all_good:
if 3 < try_count: # Tried more than 3 times without success, maybe post is in use by another program
sys.exit(1)
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create the socket
port = 80
self.sock.bind(('127.0.0.1', port)) # Bind to the interface and port we want to listen on
self.sock.listen(5)
all_good = True
break
except socket.error:
print('Socket connection error... Waiting 10 seconds to retry.')
del self.sock
time.sleep(10)
try_count += 1
print('Server is listening for incoming connections.')
print('Try to connect through the command line with:')
print('telnet localhost 80')
print('and then type whatever you want.')
print()
print("typing 'bye' finishes the thread. but not the server",)
print("eg. you can quit telnet, run it again and get a different ",)
print("thread name")
print("typing 'quit' finishes the server")
try:
while not QUIT:
try:
self.sock.settimeout(0.500)
client = self.sock.accept()[0]
except socket.timeout:
time.sleep(1)
if QUIT:
print('Received quit command. Shutting down...')
break
continue
new_thread = ClientThread(client)
print('Incoming Connection. Started thread ',)
print(new_thread.getName())
self.thread_list.append(new_thread)
new_thread.start()
for thread in self.thread_list:
if not thread.isAlive():
self.thread_list.remove(thread)
thread.join()
except KeyboardInterrupt:
print('Ctrl+C pressed... Shutting Down')
except Exception as err:
print('Exception caught: %s\nClosing...' % err)
for thread in self.thread_list:
thread.join(1.0)
self.sock.close()
if "__main__" == __name__:
server = Server()
server.run()
print('Terminated')
注:
這是在Python 3.4
創建我用Pycharm作爲我的IDE。
整體的一部分。
2.所以我創建一個雷電探測系統,這是我期望它做:
-監聽的端口路由器永遠
以上是做了,從文本文件發送完成這也是短信
拉數 - 但這個問題在問題描述1.
。
-發送HTTP GET/POST端口路由器
這樣做的問題是,我不知道該如何,如果我發送此二進制形式的路由器將採取行動,我懷疑它不會事上,輸入通過GSM發送的命令是特定的。有些時候可能需要澄清一些問題。
- 從路由器和異常收到回覆管理
-監聽對嚴重或接近罷工警告報警繼電器跳閘。
-如果跳閘,從文本文件
這將消息發送到手機存儲將是HTTP GET /指稱發送帖子。
- 從路由器的答覆,表示消息等待已發送,異常處理,如果不是這種情況
- 啓動
有我想了幾個問題回去一些關於這方面的背景知識很難通過舊谷歌找到,並在這裏找到答案。
如何從另一個文件中的另一個進程獲取來自路由器的接收數據?我想我可以寫入一個文本文件並調用這些數據,但我寧願不要。
如何多進程和使用哪種方法。
如何根據路由器手冊將http get/post發送到路由器上的套接字,如下所示:例如,
"http://192.168.1.1/cgi-bin/sms_send?number=0037061212345&text=test"
注意:在Python 3.4/Pycharm IDE上使用套接字,線程,sys和時間。
使用的雷電探測器是帶有RLO繼電器的LD-250。
使用RUT500 Teltonica路由器。
任何方向/評論,發現的錯誤,任何我大大缺失將不勝感激!非常感謝你提前:D大力鼓勵D建設性的批評!