473,326 Members | 2,095 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Howto? popen4("python -u script.py") redirected to a gui window

Short description: Using a wxPython based app, I would like to take a
python script in an editor window, invoke the python interpreter and
use another window as stdin/stdout/stderr.

Based on what I've read so far, I've figured that I need to do
something like:
f_in, f_out = popen4("python -u script.py")
where I have extracted the text from the editor and put it in
"script.py". (However, see below).

What I don't understand is how to link f_in, f_out somehow to a
different window which can be used to interact with the user.

I need a solution that will work on *nix, Windows and MacOS.

Although I am not familar with Tkinter, I most likely could figure out
what to do from an example that would use it.

Wish#1: It would be nice not to have to create the intermediate file
"script.py" and pass directly the content of the editor window to
popen4(). I know about the "-c" option for Python, but I can't see
how it would work if the script contains quotes or double quotes.

Wish#2: It would be *really nice* if, somehow, request for input [which
should arise only from raw_input() ... and, perhaps input()] by Python
could be redirected to an appropriate wxPython dialog instead of just a
window. I might be able to figure that one on my own, if I can get
enough information to get the basic redirection to a window working.

André

Jan 28 '06 #1
2 3179
Earlier this evening, I wrote:
Short description: Using a wxPython based app, I would like to take a
python script in an editor window, invoke the python interpreter and
use another window as stdin/stdout/stderr.

[snip]
Ok, I got almost everything working ... except the stdin redirection.
I'm stuck with simple (!?) IOError that I don't understand.

[leading "." added to each line below to preserve indentation]
===Simple script that I try to execute===
..def hello():
.. print "Hello world!"
..
..hello()
..test = raw_input("Give me a command: ")
..hello()
..print test

===Sample output====
Hello world!
Traceback (most recent call last):
File "E:\Python\rurple0.9.0.1\rur_py\editor.py", line 303, in
RunProgram
f_i.write(user_response)
IOError: [Errno 22] Invalid argument

===method that executes the script===
.. def RunProgram(self, event):
.. user_code = self.GetText()
.. user_code = parser.FixLineEnding(user_code)
..
.. # redefine raw_input() if present so we can call a dialog
.. if user_code.find(' raw_input(') != -1 or \
.. user_code.find('=raw_input(') != -1:
.. user_code = user_code.replace(' raw_input(', '
my_raw_input(')
.. user_code = user_code.replace('=raw_input(',
'=my_raw_input(')
.. raw_input_warning = '# # take care of raw_input # #'
.. my_raw_input = """def my_raw_input(prompt=''):
.. print '%s'+prompt\n"""%raw_input_warning
.. user_code = my_raw_input + user_code
..
.. # create temporary file to store the code
.. filename = '_last_run.py'
.. f = open(filename, 'w')
.. f.write(user_code)
.. f.close()
..
.. #redirect stdout/sdterr
.. self.parent.log.redirect()
.. f_i, f_o = os.popen4("python -u %s"%filename)
.. output_lines = f_o.readlines()
. length = len(output_lines)
.. while length > 0:
.. line = output_lines.pop(0)
.. if line.find(raw_input_warning) != -1:
.. stripped_line = line.replace(raw_input_warning, '')
.. dlg = wx.TextEntryDialog(self, stripped_line[:-1],
.. 'Handling raw_input()', '')
.. if dlg.ShowModal() == wx.ID_OK:
.. user_response = dlg.GetValue() #+ '\n'
.. dlg.Destroy()
.. f_i.write(user_response)
.. else:
.. print line,
.. output_lines += f_o.readlines()
.. length = len(output_lines)
..
.. self.parent.log.redirect('reset')
======================================

The wx.TextEntryDialog gets called properly.
After I enter the text in it ("user_response"),
I get the quoted error message.

Suggestions anyone?

André

Jan 28 '06 #2
Sorry about the single-author thread; I have been googling for answers
and trying out for 3 nights... I just want to record to save others the
trouble.
Earlier this evening, I wrote:
Short description: Using a wxPython based app, I would like to take a
python script in an editor window, invoke the python interpreter and
use another window as stdin/stdout/stderr.

[snip]

I used "exec" instead of popen and solved it. I had tried originally
with exec but then read that exec could not handle "raw_input", so I
gave up too quickly.

Here are the main parts of the solution.
===============
.. def RunProgram(self, event):
.. user_code = self.GetText()
.. user_code = parser.FixLineEnding(user_code)
.. #redirect stdout/sdterr by redefining them
.. self.parent.log.redirect()
.. myGlobals = globals()
.. myGlobals['raw_input'] = self.myRawInput
.. myGlobals['input'] = self.myInput
.. exec user_code in myGlobals
.. self.parent.log.redirect('reset')

.. def myRawInput(self, text):
.. dlg = wx.TextEntryDialog(self, text,
.. 'Handling raw_input()', '')
.. if dlg.ShowModal() == wx.ID_OK:
.. user_response = dlg.GetValue() + '\n'
.. dlg.Destroy()
.. return user_response
..
.. def myInput(self, text):
.. dlg = wx.TextEntryDialog(self, text,
.. 'Handling input()', '')
.. if dlg.ShowModal() == wx.ID_OK:
.. user_response = dlg.GetValue() + '\n'
.. dlg.Destroy()
.. return eval(user_response)
===
..class LogWindow(wx.TextCtrl):
.. def __init__ (self, parent):
.. wx.TextCtrl.__init__(self, parent, -1,
.. style=wx.TE_MULTILINE|wx.TE_READONLY)
.. def redirect(self, option=''):
.. if option == "reset":
.. sys.stdout = sys.__stdout__
.. sys.stderr = sys.__stderr__
.. else:
.. sys.stdout = self
.. sys.stderr = self

Jan 28 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Greg Kuperberg | last post by:
I want to run subprocesses with limits on the execution time and the output size of the subprocess. If the subprocess exceeds limits, then the parent should kill it gracefully (SIGTERM rather than...
12
by: Stéphane Ninin | last post by:
Hi all, This is not the first time I see this way of coding in Python and I wonder why this is coded this way: Howto on PyXML (http://pyxml.sourceforge.net/topics/howto/node14.html) shows it...
0
by: python-help-bounces | last post by:
Your message for python-help@python.org, the Python programming language assistance line, has been received and is being delivered. This automated response is sent to those of you new to...
1
by: Vivien Mallet | last post by:
Hello, I use popen2.Popen4 and I experienced problems with it. Let me show you with an example. The following script is called "lines" (it prints lines of 'X'): ---------------------...
1
by: qwejohn | last post by:
Hello, I had posted this question in the twisted mailing list but did not got a solution ; I hope that the python Gurus of this forum can help me a bit. I am trying the exmaple in the python...
3
by: z0mb1e_fr | last post by:
I am writing a script to change a router config. The config is long and the result is that the display stops with a "--more--". Normally we type return to go to a new line or the space bar to go...
45
by: Gregory Petrosyan | last post by:
1) From 2.4.2 documentation: There are two new valid (semantic) forms for the raise statement: raise Class, instance raise instance 2) In python: >>> raise NameError Traceback (most recent...
13
by: Jim | last post by:
Could somebody tell me why I need the "elif char == '\n'" in the following code? This is required in order the pick up lines with just spaces in them. Why doesn't the "else:" statement pick this...
5
by: Nicolas Pontoizeau | last post by:
Hi, I am handling a mixed languages text file encoded in UTF-8. Theres is mainly French, English and Asian languages. I need to detect every asian characters in order to enclose it by a special...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.