将值从一个Python程序传递到另一个 [英] Passing values from one Python program to another

查看:266
本文介绍了将值从一个Python程序传递到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了使用诸如.txt/dummy文件之类的东西以外,是否有可能将值从一个程序传递到另一个程序?

我有一个程序使用.txt文件将起始值传递给另一个程序.每次运行程序之间,我都会在两次启动程序之间更新文件中的值(十次,基本上同时).这样做很好,但是我想让'child'程序在完成后再向'mother'程序报告,并且还向报告其发现要下载的文件.

是否可以在不使用11个文件的情况下执行此操作(对于孩子"到母亲"报告的每个实例一个文件,而对于母亲"到孩子"报告的每个文件一个文件)?我说的是完全独立的程序,而不是类或函数之类的东西.

要高效地运行,而不是等待数小时才能完成所有工作,我需要子"程序运行十次,并以更快的速度完成工作.因此,我运行了十次子程序,并给每个程序一个单独的范围以进行检查.

两个程序都可以正常运行,但我想让它们彼此来回运行/报告,并希望不要使用文件传输"来完成任务,尤其是在传输文件的子母方面.数据.

母亲"计划...当前

import os
import sys
import subprocess
import time

os.chdir ('/media/')

#find highest download video
Hival = open("Highest.txt", "r") 
Histr = Hival.read()
Hival.close()
HiNext = str(int(Histr)+1)

#setup download #1
NextVal = open("NextVal.txt","w")
NextVal.write(HiNext)
NextVal.close()

#call download #1
procs=[]
proc=subprocess.Popen(['python','test.py'])
procs.append(proc)
time.sleep(2)

#setup download #2-11
Histr2 = int(Histr)/10000
Histr2 = Histr2 + 1

for i in range(10):
    Hiint = str(Histr2)+"0000"
    NextVal = open("NextVal.txt","w")
    NextVal.write(Hiint)
    NextVal.close()

    proc=subprocess.Popen(['python','test.py'])
    procs.append(proc)
    time.sleep(2)
    Histr2 = Histr2 + 1

for proc in procs:
    proc.wait()

儿童"计划

import urllib
import os
from Tkinter import *
import time

root = Tk()
root.title("Audiodownloader")
root.geometry("200x200")

app = Frame(root)
app.grid()

os.chdir('/media/')
Fileval = open('NextVal.txt','r')
Fileupdate = Fileval.read()
Fileval.close()
Fileupdate = int(Fileupdate)
Filect = Fileupdate/10000
Filect2 = str(Filect)+"0009"
Filecount = int(Filect2)
while Fileupdate <= Filecount:
    root.title(Fileupdate)
    url = 'http://www.yourfavoritewebsite.com/audio/encoded/'+str(Fileupdate)+'.mp3'
    urllib.urlretrieve(url,str(Fileupdate)+'.mp3')
    statinfo = os.stat(str(Fileupdate)+'.mp3')
    if statinfo.st_size<10000L: 
        os.remove(str(Fileupdate)+'.mp3')

    time.sleep(.01)
    Fileupdate = Fileupdate+1
    root.update_idletasks()

我正在尝试将原始VB6程序转换为Linux,并使其更易于同时使用.因此缺少.mainloop的缺失.这是我第一次真正尝试使用Python进行任何操作,因此缺少def或类.在1.5个月不做任何操作之后,我试图返回并完成此操作,主要是因为不知道如何做.不久前,在研究中,我发现这很困难.我从来没有做过线程/套接字/客户端/服务器交互的任何事情,所以在这种情况下我纯粹是个白痴. Google上的所有内容,我都被带回了这里.

是的,我希望同时运行10个该程序的副本,以节省时间.如果程序可以向母亲"报告,则我可以不使用gui界面,以便母亲可以在屏幕上打印正在搜索的当前值.以及孩子可以在完成时报告是否成功,以及是否有任何文件成功下载(由于文件太小,因此先下载然后删除).下次程序运行时,我将使用成功的下载信息来更新Highest.txt.

我认为这可能会更好地说明问题……或者我不了解使用服务器/客户端交互的本质:)程序中的唯一原因time.sleep是由于试图确保文件可能在子程序的下一个实例运行之前被编写.我不确定我可能会遇到哪种计时问题,因此为了安全起见我将这些行包括在内.

解决方案

这可以通过使用多处理库的简单客户端/服务器拓扑来实现.使用您的母子术语:

server.py

from multiprocessing.connection import Listener

# client
def child(conn):
    while True:
        msg = conn.recv()
        # this just echos the value back, replace with your custom logic
        conn.send(msg)

# server
def mother(address):
    serv = Listener(address)
    while True:
        client = serv.accept()
        child(client)

mother(('', 5000))

client.py

from multiprocessing.connection import Client

c = Client(('localhost', 5000))

c.send('hello')
print('Got:', c.recv())

c.send({'a': 123})
print('Got:', c.recv())

运行方式

$ python server.py
$ python client.py

Is it possible -- other than by using something like a .txt/dummy file -- to pass a value from one program to another?

I have a program that uses a .txt file to pass a starting value to another program. I update the value in the file in between starting the program each time I run it (ten times, essentially simultaneously). Doing this is fine, but I would like to have the 'child' program report back to the 'mother' program when it is finished, and also report back what files it found to download.

Is it possible to do this without using eleven files to do it (that's one for each instance of the 'child' to 'mother' reporting, and one file for the 'mother' to 'child')? I am talking about completely separate programs, not classes or functions or anything like that.

To operate efficently, and not be waiting around for hours for everything to complete, I need the 'child' program to run ten times and get things done MUCH faster. Thus I run the child program ten times and give each program a separate range to check through.

Both programs run fine, I but would like to get them to run/report back and forth with each other and hopefully not be using file 'transmission' to accomplish the task, especially on the child-mother side of the transferring of data.

'Mother' program...currently

import os
import sys
import subprocess
import time

os.chdir ('/media/')

#find highest download video
Hival = open("Highest.txt", "r") 
Histr = Hival.read()
Hival.close()
HiNext = str(int(Histr)+1)

#setup download #1
NextVal = open("NextVal.txt","w")
NextVal.write(HiNext)
NextVal.close()

#call download #1
procs=[]
proc=subprocess.Popen(['python','test.py'])
procs.append(proc)
time.sleep(2)

#setup download #2-11
Histr2 = int(Histr)/10000
Histr2 = Histr2 + 1

for i in range(10):
    Hiint = str(Histr2)+"0000"
    NextVal = open("NextVal.txt","w")
    NextVal.write(Hiint)
    NextVal.close()

    proc=subprocess.Popen(['python','test.py'])
    procs.append(proc)
    time.sleep(2)
    Histr2 = Histr2 + 1

for proc in procs:
    proc.wait()

'Child' program

import urllib
import os
from Tkinter import *
import time

root = Tk()
root.title("Audiodownloader")
root.geometry("200x200")

app = Frame(root)
app.grid()

os.chdir('/media/')
Fileval = open('NextVal.txt','r')
Fileupdate = Fileval.read()
Fileval.close()
Fileupdate = int(Fileupdate)
Filect = Fileupdate/10000
Filect2 = str(Filect)+"0009"
Filecount = int(Filect2)
while Fileupdate <= Filecount:
    root.title(Fileupdate)
    url = 'http://www.yourfavoritewebsite.com/audio/encoded/'+str(Fileupdate)+'.mp3'
    urllib.urlretrieve(url,str(Fileupdate)+'.mp3')
    statinfo = os.stat(str(Fileupdate)+'.mp3')
    if statinfo.st_size<10000L: 
        os.remove(str(Fileupdate)+'.mp3')

    time.sleep(.01)
    Fileupdate = Fileupdate+1
    root.update_idletasks()

I'm trying to convert the original VB6 program over to Linux and make it much easier to use at the same time. Hence the lack of .mainloop being missing. This was my first real attempt at anything in Python at all hence the lack of def or classes. I'm trying to come back and finish this up after 1.5 months of doing nothing with it mostly due to not knowing how to. In research a little while ago I found this is WAY over my head. I haven't ever did anything with threads/sockets/client/server interaction so I'm purely an idiot in this case. Google anything on it and I just get brought right back here to stackoverflow.

Yes, I want 10 running copies of the program at the same time, to save time. I could do without the gui interface if it was possible for the program to report back to 'mother' so the mother could print on the screen the current value that is being searched. As well as if the child could report back when its finished and if it had any file that it downloaded successfully(versus downloaded and then erased due to being to small). I would use the successful download information to update Highest.txt for the next time the program got ran.

I think this may clarify things MUCH better...that or I don't understand the nature of using server/client interaction:) Only reason time.sleep is in the program was due to try to make sure that the files could get written before the next instance of the child program got ran. I didn't know for sure what kind of timing issue I may run into so I included those lines for safety.

解决方案

This can be implemented using a simple client/server topology using the multiprocessing library. Using your mother/child terminology:

server.py

from multiprocessing.connection import Listener

# client
def child(conn):
    while True:
        msg = conn.recv()
        # this just echos the value back, replace with your custom logic
        conn.send(msg)

# server
def mother(address):
    serv = Listener(address)
    while True:
        client = serv.accept()
        child(client)

mother(('', 5000))

client.py

from multiprocessing.connection import Client

c = Client(('localhost', 5000))

c.send('hello')
print('Got:', c.recv())

c.send({'a': 123})
print('Got:', c.recv())

Run with

$ python server.py
$ python client.py

这篇关于将值从一个Python程序传递到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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