Dear list,
I have a long list of commands in the form of a script and would like to
obtain a log file as if I enter the commands one by one. (The output
will be used in a tutorial.) What would be the best way to do it? Copy
and paste is not acceptable since I make frequent changes tot he script.
Many thanks in advance.
Bo 7 1869
Bo Peng wrote: I have a long list of commands in the form of a script and would like to obtain a log file as if I enter the commands one by one. (The output will be used in a tutorial.) What would be the best way to do it? Copy and paste is not acceptable since I make frequent changes tot he script.
the first example on this page http://effbot.org/librarybook/code.htm
shows how to execute Python code line by line.
here's a variation that echoes the script fragments with the right prompts
in front of them:
import code
SCRIPT = [line.rstrip() for line in open("myscript. py")]
script = ""
prompt = ">>>"
for line in SCRIPT:
print prompt, line
script = script + line + "\n"
co = code.compile_co mmand(script, "<stdin>", "exec")
if co:
# got a complete statement. execute it!
exec co
script = ""
prompt = ">>>"
else:
prompt = "..."
</F>
The 'code' module contains 'Utilities needed to emulate Python's interactive
interpreter.'. By subclassing code.Interactiv eConsole and replacing the
raw_input method with one which reads from a file, I think you can get what you
want.
The example below the classes uses StringIO so that it can be self-contained,
but you'll probably use a regular file instead.
import code, sys
class BoPeng(code.Int eractiveConsole ):
def __init__(self, locals=None, filename="<cons ole>", file = None):
self.file = file or open(filename)
code.Interactiv eConsole.__init __(self, locals, filename)
def raw_input(self, prompt):
l = self.file.readl ine()
if l == '': raise EOFError
sys.stdout.writ e(prompt + l)
return l.strip("\n")
session = '''\
print 3+3
for i in range(10):
print i
print "Example of a traceback:"
1/0
'''
import StringIO
b = BoPeng(file = StringIO.String IO(session))
b.interact(None )
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.6 (GNU/Linux)
iD8DBQFDLYekJd0 1MZaTXX0RAnf4AK CU84FVVK+2pgx3y QS5IBQcoK6wwACg mMaM
8zYxjYispPtHhkn nges00UE=
=yUXD
-----END PGP SIGNATURE-----
Thank you for the suggestions and code! import code
SCRIPT = [line.rstrip() for line in open("myscript. py")]
script = "" prompt = ">>>"
for line in SCRIPT: print prompt, line script = script + line + "\n" co = code.compile_co mmand(script, "<stdin>", "exec") if co: # got a complete statement. execute it! exec co script = "" prompt = ">>>" else: prompt = "..."
This one fails at function definition.
def fun():
a=1
b=2 <--- not included.
Still trying other methods.
Bo je****@unpython ic.net wrote: The 'code' module contains 'Utilities needed to emulate Python's interactive interpreter.'. By subclassing code.Interactiv eConsole and replacing the raw_input method with one which reads from a file, I think you can get what you want.
This method works fine with only one minor problem. It would stop
(waiting for user input) at help(str) command. I will have to find a way
to feed the program with'q' etc.
Bo
Bo Peng wrote: import code
SCRIPT = [line.rstrip() for line in open("myscript. py")]
script = "" prompt = ">>>"
for line in SCRIPT: print prompt, line script = script + line + "\n" co = code.compile_co mmand(script, "<stdin>", "exec") if co: # got a complete statement. execute it! exec co script = "" prompt = ">>>" else: prompt = "..."
This one fails at function definition.
def fun(): a=1 b=2 <--- not included.
hmm. looks like a bug in compile_command . stripping off the trailing
newline seems to fix it:
co = code.compile_co mmand(script[:-1], "<stdin>", "exec")
(to make things look right, you need to add an empty line after each
function definition in your code)
</F>
Bo Peng wrote: This method works fine with only one minor problem. It would stop (waiting for user input) at help(str) command. I will have to find a way to feed the program with'q' etc.
replacing sys.stdin with something that isn't a TTY will fix this.
here's one way to do it:
class wrapper:
def __init__(self, file):
self.file = file
def isatty(self):
return 0
def __getattr__(sel f, key):
return getattr(self.fi le, key)
sys.stdin = wrapper(sys.std in)
</F>
Fredrik Lundh wrote: replacing sys.stdin with something that isn't a TTY will fix this.
This works like magic! Thank you!
Bo This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Miki Tebeka |
last post by:
Hello All,
If there a way a script can tell Python to enter interactive mode even if
the -i command line switch was not given?
I want py2exe to create an interactive session, without writing my own
REPL.
Thanks.
--
|
by: Joe |
last post by:
When you run "python -i scriptname.py" after the script completes you left
at the interactive command prompt.
Is there a way to have this occur from a running program?
In other words can I just run scriptname.py (NOT python -i scriptname.py)
and inside of scriptname.py I decide that I want to fall back to the
interactive prompt?
I've searched and so far the only thing I've come up with is to use pdb, but
|
by: siggy2 |
last post by:
Hi All,
(sorry for my bad english)
I wrote a __tiny__ and __stupid__ recursive script directly into
pythonwin
interactive window with a time.sleep(1) and a print before each
recursion...
I should have taken a closer look at the ending condition (never
satisfied!),
anyway I was quite confident that a control-C would have stopped the
intepreter as it is (incidentally?) when this break sequence is entered
|
by: WJ |
last post by:
I have three ASPX pages:
1. "WebForm1.aspx" is interactive, responsible for calling a web site
(https://www.payMe.com) with $$$. It is working fine.
2. "WebForm2.aspx" is non-interactive, a listener in my site to capture a
"STATUS_CD" returned by www.payMe.com. It is working fine.
3. "WebForm3.aspx" is interactive page, responsibe to display the STATUS
CODE "POSTED" by "WebForm2.aspx".
4. My goal is to use "WebForm2.aspx" to call...
|
by: Adam Blinkinsop |
last post by:
I'm writing a set of modules to monitor remote system services, and I'm
having a problem running my test scripts. When I pass the scripts into
python, like so:
--
$ PYTHONPATH="${TARGET_DIR}" python test.py
--
I get an ImportError:
| |
by: Jonathan Mark |
last post by:
Some languages, such as Scheme, permit you to make a transcript of an
interactive console session. Is there a way to do that in Python?
|
by: boris.smirnov |
last post by:
Hi there,
I have a problem with setting environment variable in my script that
uses qt library. For this library I have to define a path to tell the
script whre to find it.
I have a script called "shrink_bs_070226" that looks like this:
**********************************
import sys, re, glob, shutil
import os
|
by: Joshua J. Kugler |
last post by:
Yes, I've read this:
http://mail.python.org/pipermail/python-list/2006-August/395943.html
That's not my problem.
I installed PlanetPlanet <http://www.planetplanet.org/via the
package's "setup.py install" command (as root). planet.py will not run,
however, giving me this error:
Traceback (most recent call last):
File "/usr/local/bin/planet.py", line 167, in ?
|
by: Anthony |
last post by:
Hi, I'm a FoxPro programmer, but I want to learn python before it's
too late. I do a lot of statistical programming, so I import SPSS
into python. In my opinion, the best features of Visual FoxPro 9.0
were:
a) Intellisense (tells you what classes/methods are available and what
variables go into a function)
b) Code Completion (guesses your code after four letters)
c) Data-Orientation; multiple data sessions can be open, data can be...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |