473,573 Members | 2,388 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Easy "here documents" ??

I've done some Googling around on this and it seems like creating a here
document is a bit tricky with Python. Trivial via triple-quoted strings
if there's no need for variable interpolation but requiring a long, long
formatted arglist via (%s,%s,%s,ad infinitum) if there is. So my
question is:

Is there a way to produce a very long multiline string of output with
variables' values inserted without having to resort to this wacky

"""v = %s"""%(variable )

business?

Thanks,
Jim, Python no0b
--
"I regard NASCAR the same way I regard gay porn: I know it exists and I
know some guys like it; I just don't want to see it." -- Z. B. Goode
Jul 18 '05 #1
33 9133
Jim Hill wrote:
I've done some Googling around on this and it seems like creating a here
document is a bit tricky with Python. Trivial via triple-quoted strings
if there's no need for variable interpolation but requiring a long, long
formatted arglist via (%s,%s,%s,ad infinitum) if there is. So my
question is:

Is there a way to produce a very long multiline string of output with
variables' values inserted without having to resort to this wacky

"""v = %s"""%(variable )

business?


I have no idea what a "here document" is, but there are several
alternatives to the "wacky" basic substitution with a tuple of
values.

The simplest uses a mapping type:

mydict = {'namedVal': 666}
'''v = %(namedVal)s''' % mydict

Does that let you build whatever a "here document" is?
Jul 18 '05 #2
I was curious so I googled , looks like a unix thing :)

http://www.faqs.org/docs/abs/HTML/here-docs.html

Ok I am with Peter on this , still clueless.
What about string replacement.

py> x = """ Hello me name is ~NAME~. \n I am ~AGE~ years old.\n
.... I live in ~CITY~.\n The city of ~CITY~ is nice.\n
.... I have live here for ~AGE~ years.\n
.... """
py> x = x.replace('~AGE ~', '12')
py> x = x.replace('~NAM E~', 'Jimmy')
py> x = x.replace('~CIT Y~', 'Oma')

It makes your template cleaner cause you can use what you want
for the tokens, but takes more lines to do the replacements.
still clueless,
M.E.Farmer
Peter Hansen wrote:
Jim Hill wrote:
I've done some Googling around on this and it seems like creating a here document is a bit tricky with Python. Trivial via triple-quoted strings if there's no need for variable interpolation but requiring a long, long formatted arglist via (%s,%s,%s,ad infinitum) if there is. So my
question is:

Is there a way to produce a very long multiline string of output with variables' values inserted without having to resort to this wacky

"""v = %s"""%(variable )

business?


I have no idea what a "here document" is, but there are several
alternatives to the "wacky" basic substitution with a tuple of
values.

The simplest uses a mapping type:

mydict = {'namedVal': 666}
'''v = %(namedVal)s''' % mydict

Does that let you build whatever a "here document" is?


Jul 18 '05 #3
Peter Hansen wrote:
Jim Hill wrote:
I've done some Googling around on this and it seems like creating a here
document is a bit tricky with Python. Trivial via triple-quoted strings
if there's no need for variable interpolation but requiring a long, long
formatted arglist via (%s,%s,%s,ad infinitum) if there is. So my
question is:

Is there a way to produce a very long multiline string of output with
variables' values inserted without having to resort to this wacky

"""v = %s"""%(variable )

business?

I have no idea what a "here document" is, but there are several
alternatives to the "wacky" basic substitution with a tuple of
values.


OP is looking for "heredoc" syntax; in, let's say, PHP
this lets you do something like:

$foo = new foo();
$name = 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;

AFAIK, there is no direct Python equivalent for this kind of syntax.
Using a mapping like you suggested or the string.Template class in
Python 2.4 still maybe improvements over what OP calls that "wacky"
business.

--
Vincent Wehren

The simplest uses a mapping type:

mydict = {'namedVal': 666}
'''v = %(namedVal)s''' % mydict

Does that let you build whatever a "here document" is?

Jul 18 '05 #4
Jim Hill wrote:
Is there a way to produce a very long multiline string of output with
variables' values inserted without having to resort to this wacky

"""v = %s"""%(variable )

business?


Try combining Python 2.4's subprocess module with its string Templates.

Cheers,
Nick.

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #5
ji*****@swcp.co m (Jim Hill) writes:
I've done some Googling around on this and it seems like creating a here
document is a bit tricky with Python. Trivial via triple-quoted strings
if there's no need for variable interpolation but requiring a long, long
formatted arglist via (%s,%s,%s,ad infinitum) if there is. So my
question is:

Is there a way to produce a very long multiline string of output with
variables' values inserted without having to resort to this wacky

"""v = %s"""%(variable )
business?


Hmmmmmm, by using the %(varname)[dsf...] with vars(), locals(),
globals(), someDict, et al, a little messy but not terribly difficult.

It gets uglier though if you want to do this from inside a function
and have variables from more than one scope interpolated. For that
you need something that can treat a series of dicts as one.If there's
built in functionality in Python for this, I haven't discovered it
yet.

To wit;

# feed this thing with one or more dicts, in order of decreasing
#search priority.
class multiDict:
def __init__(self, *dicts):
self.dicts = dicts
def __getitem__(sel f, key):
for dict in self.dicts:
if dict.has_key(ke y):
return dict[key]
raise(KeyError)

globalvar = 100

def foo():
localvar = 200

print """
%(globalvar)d
%(localvar)d
""" % multiDict(globa ls(), locals())

foo()

------------------

Now all else that we need to make this pretty would be macros, a la
cpp m4 or similar

define(`VARS', `multiDict(loca ls(), globals())')

print "..." % VARS

You get the idea.
--
-------------------------------------------------------------------------------
Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant
305 321-1144 (mobile http://www.JerrySievers.com/
Jul 18 '05 #6
Jerry Sievers wrote:
It gets uglier though if you want to do this from inside a function
and have variables from more than one scope interpolated. For that
you need something that can treat a series of dicts as one.If there's
built in functionality in Python for this, I haven't discovered it
yet.


you use them all the time: plain old instance objects...

here's a rather horrid piece of code that turns a list of dictionaries
into a single object the automatically searches the dictionary chain
when you ask for attributes (use getattr for non-standard keys).

def flatten_dicts(* dicts):
root = None
for dict in dicts:
class wrapper: pass
if root:
wrapper.__bases __ = (root,)
wrapper.__dict_ _ = dict
root = wrapper
return wrapper()

obj = flatten_dicts(d 1, d2, d3)

</F>

Jul 18 '05 #7
Jim Hill <ji*****@swcp.c om> wrote:
I've done some Googling around on this and it seems like creating a here
document is a bit tricky with Python. Trivial via triple-quoted strings
if there's no need for variable interpolation but requiring a long, long
formatted arglist via (%s,%s,%s,ad infinitum) if there is. So my
question is:

Is there a way to produce a very long multiline string of output with
variables' values inserted without having to resort to this wacky

"""v = %s"""%(variable )


I prefer this
amount = 1
cost = 2.0
what = 'potato'
print """\ ... I'll have %(amount)s %(what)s
... for $%(cost)s please""" % locals()
I'll have 1 potato
for $2.0 please
Its almost as neat as perl / shell here documents and emacs parses """
strings properly too ;-)

Note the \ after the triple quote so the first line is flush on the
left, and the locals() statement. You can use globals() or a
dictionary you might have lying around instead which is much more
flexible than perl. You can even pass self.__dict__ if you are in a
class method so you can access attributes.
class A: pass ... a=A()
a.amount=10
a.what="rutabag a"
a.cost=17.5
print """\ ... I'll have %(amount)s %(what)s
... for $%(cost)s please""" % a.__dict__
I'll have 10 rutabaga
for $17.5 please


--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick
Jul 18 '05 #8
Jim Hill wrote:
I've done some Googling around on this and it seems like creating a here
document is a bit tricky with Python. Trivial via triple-quoted strings
if there's no need for variable interpolation but requiring a long, long
formatted arglist via (%s,%s,%s,ad infinitum) if there is. So my
question is:

Is there a way to produce a very long multiline string of output with
variables' values inserted without having to resort to this wacky


I was thinking about this. But I can't think of any reason why you would
want to do this in Python. What's wrong with a regular parameterized
function?
--
-- ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~
Keith Dart <kd***@kdart.co m>
public key: ID: F3D288E4
=============== =============== =============== =============== =========
Jul 18 '05 #9
Fredrik Lundh wrote:
Jerry Sievers wrote:

It gets uglier though if you want to do this from inside a function
and have variables from more than one scope interpolated. For that
you need something that can treat a series of dicts as one.If there's
built in functionality in Python for this, I haven't discovered it
yet.

you use them all the time: plain old instance objects...

here's a rather horrid piece of code that turns a list of dictionaries
into a single object the automatically searches the dictionary chain
when you ask for attributes (use getattr for non-standard keys).

def flatten_dicts(* dicts):
root = None
for dict in dicts:
class wrapper: pass
if root:
wrapper.__bases __ = (root,)
wrapper.__dict_ _ = dict
root = wrapper
return wrapper()

obj = flatten_dicts(d 1, d2, d3)

Iterative subclassing, yet. Yerch :-) It's sometimes amazing just how
down and dirty Python will let you get.

Of course, if the mappings were all dictionaries then it would be rather
simpler to just update an empty dict with the outermost through to the
innermost scopes.

though-efficiency-would-be-determined-by-usage-ly y'rs - steve
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
Jul 18 '05 #10

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

Similar topics

27
8017
by: Tom Rodman | last post by:
I want to embed a bash script inside the c program. How could you do the below bash snippet in "c"?: cat > /tmp/foo <<\__EOD_ all kinds of nasty stuff in here including single and double quotes and bashslashes .. (note that the here doc delimiter is preceded by a "\" __EOD_
6
13260
by: JuLiE Dxer | last post by:
Is there a way via C# to programmatically retrieve the full path name to folders like "My Documents" ?? I'm seeing examples with the use of Shell32 stuff I believe, SHGetSpecialFolderLocation and I have no knowledge nor experience using such stuff. I've seen some examples pertaining to these special folders but it's all Greek to me and...
4
6545
by: Ben | last post by:
Hello, I need to save some information into a text file. For this, I use : FileOpen(1, "c:\MyFile.txt", OpenMode.Output) For I = 0 To iCpt - 1 WriteLine(1, myDs.Tables(0).Rows(I).Item("MyText")) Next FileClose(1)
0
7747
marktang
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...
0
7670
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...
1
7740
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...
0
8036
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6363
agi2029
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...
0
3706
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...
0
3703
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2167
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1005
bsmnconsultancy
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...

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.