473,698 Members | 2,152 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

building strings with variable input

Sometimes if find it clumsy unsing the following approach building strings:

cmd = "%s -start %s -end %s -dir %s" % (executable, startTime, endTime,
directory)

Especially if you have a lot of variable input it makes it hard to match
the variables to the proper fields. From other scripting languanges I'm
used to something like:

$cmd = "$executabl e -start $startTime -end $endTime -dir $directory"

This makes it very easy to see how the string is actually built. You
dont't have to worry where which variables go.

Is there a similar way to do this in python?

Thanks,
Olaf
Jul 18 '05 #1
8 1980
Olaf Meyer wrote:
Especially if you have a lot of variable input it makes it hard to
match
the variables to the proper fields. From other scripting languanges
I'm
used to something like:

$cmd = "$executabl e -start $startTime -end $endTime -dir $directory"

This makes it very easy to see how the string is actually built. You
dont't have to worry where which variables go.

Is there a similar way to do this in python?


Sure:

cmd = "%(executab le)s -start %(startTime)s -end %(endTime)s -dir
%(directory)s" % locals()

There are also more expansive solutions such as YAPTU or EmPy.

Note, however, that what you are trying to do (presuming you're passing
this to os.system or something similar) is potentially a serious
security risk. If the values of the strings you are constructing the
command line are not fully trustworthy, they can be easily manipulated
to make your program execute arbitrary shell commands.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ In the fight between you and the world, back the world.
-- Frank Zappa
Jul 18 '05 #2
Olaf Meyer wrote:
Sometimes if find it clumsy unsing the following approach building
strings:

cmd = "%s -start %s -end %s -dir %s" % (executable, startTime, endTime,
directory)

Especially if you have a lot of variable input it makes it hard to match
the variables to the proper fields. From other scripting languanges I'm
used to something like:

$cmd = "$executabl e -start $startTime -end $endTime -dir $directory"

This makes it very easy to see how the string is actually built. You
dont't have to worry where which variables go.

Is there a similar way to do this in python?

"from %(org)s to %(dest)s" % dict(org="X", dest="Y") 'from X to Y'

or even
org = "A"
dest = "B"
"from %(org)s to %(dest)s" % locals()

'from A to B'

Peter
Jul 18 '05 #3
Erik Max Francis wrote:
Olaf Meyer wrote:

Especially if you have a lot of variable input it makes it hard to
match
the variables to the proper fields. From other scripting languanges
I'm
used to something like:

$cmd = "$executabl e -start $startTime -end $endTime -dir $directory"

This makes it very easy to see how the string is actually built. You
dont't have to worry where which variables go.

Is there a similar way to do this in python?

Sure:

cmd = "%(executab le)s -start %(startTime)s -end %(endTime)s -dir
%(directory)s" % locals()

There are also more expansive solutions such as YAPTU or EmPy.

Note, however, that what you are trying to do (presuming you're passing
this to os.system or something similar) is potentially a serious
security risk. If the values of the strings you are constructing the
command line are not fully trustworthy, they can be easily manipulated
to make your program execute arbitrary shell commands.


Erik,

thanks for your solution suggestion and pointing out the security risks.
However security is not an issue in my case ;-)

Olaf
Jul 18 '05 #4
At some point, Erik Max Francis <ma*@alcyone.co m> wrote:
Olaf Meyer wrote:
Especially if you have a lot of variable input it makes it hard to
match
the variables to the proper fields. From other scripting languanges
I'm
used to something like:

$cmd = "$executabl e -start $startTime -end $endTime -dir $directory"

This makes it very easy to see how the string is actually built. You
dont't have to worry where which variables go.

Is there a similar way to do this in python?


Sure:

cmd = "%(executab le)s -start %(startTime)s -end %(endTime)s -dir
%(directory)s" % locals()

There are also more expansive solutions such as YAPTU or EmPy.

Note, however, that what you are trying to do (presuming you're passing
this to os.system or something similar) is potentially a serious
security risk. If the values of the strings you are constructing the
command line are not fully trustworthy, they can be easily manipulated
to make your program execute arbitrary shell commands.


In which case he's probably better off with his original format (almost):

cmd = '"$executabl e" -start "$startTime " -end "$endTime" -dir "$directory "'
os.environ['executable'] = 'blah'
os.environ['startTime'] = '12'
os.environ['endTime'] = '18'
os.environ['directory'] = './'
os.system(cmd)

This way, the shell handles all the quoting. You can do
del os.environ['executable']
afterwards to clean up. I got this technique from
http://freshmeat.net/articles/view/337/

For the quoting, compare:
os.environ['string'] = "`uname` $TERM"
os.system('echo "$string"') `uname` $PATH
(this is what we want: don't run arbitrary commands or expand
environment variables given in a user string)

with string = "`uname` $TERM"
os.system('echo "%s"' % string)

Linux xterm
(whoops, security leak)

--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)phy sics(dot)mcmast er(dot)ca
Jul 18 '05 #5
Erik Max Francis wrote:
Olaf Meyer wrote:

Especially if you have a lot of variable input it makes it hard to
match
the variables to the proper fields. From other scripting languanges
I'm
used to something like:

$cmd = "$executabl e -start $startTime -end $endTime -dir $directory"

This makes it very easy to see how the string is actually built. You
dont't have to worry where which variables go.

Is there a similar way to do this in python?

Sure:

cmd = "%(executab le)s -start %(startTime)s -end %(endTime)s -dir
%(directory)s" % locals()

There are also more expansive solutions such as YAPTU or EmPy.

Note, however, that what you are trying to do (presuming you're passing
this to os.system or something similar) is potentially a serious
security risk. If the values of the strings you are constructing the
command line are not fully trustworthy, they can be easily manipulated
to make your program execute arbitrary shell commands.


I just found out another way ;-) Using the locals() has the disadvantage
that I cannot use more complex variable parameters (e.g. certain values
of a dictionary). The following works well:

cmd = (executable + " -start " + startTime + " -end " + endTime +
" -dir " + options.dir)

Olaf
Jul 18 '05 #6
"David M. Cooke" wrote:
In which case he's probably better off with his original format
(almost):

cmd = '"$executabl e" -start "$startTime " -end "$endTime" -dir \
"$directory "'
os.environ['executable'] = 'blah'
os.environ['startTime'] = '12'
os.environ['endTime'] = '18'
os.environ['directory'] = './'
os.system(cmd)


This doesn't resolve the underlying possibility for mailicious people in
control of the contents of those variables to get it to execute
arbitrary shell code. (In his case he says it isn't an issue, but
still.)

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ It was involuntary. They sank my boat.
-- John F. Kennedy (on how he became a war hero)
Jul 18 '05 #7
"Tim Roberts" <ti**@probo.com > wrote in message
news:3r******** *************** *********@4ax.c om...
Olaf Meyer <no****@nospam. net> wrote:

I just found out another way ;-) Using the locals() has the disadvantage
that I cannot use more complex variable parameters (e.g. certain values
of a dictionary). The following works well:

cmd = (executable + " -start " + startTime + " -end " + endTime +
" -dir " + options.dir)


Yes, that works, but you should bear in mind that it is slower than the %s
option. The "+" operations are all separate interpreter steps, while the
"%" operation is done in C.


On the relative time scales of concatenating 7 strings compared to forking
off a separate process (which I presume is what is to be done with cmd), I'd
go for the more readable representation, to aid in long term
maintainability .

If I have some string concatenation being done in a highly repetitive part
of code, then by all means, replace it with one of the half dozen documented
optimized alternatives. But if I build a string in order to create a
sub-process, or invoke a database query, or make a remote CORBA invocation,
etc., then these "optimizati ons" don't really save much time, and instead
distract me/reviewers/testers/maintainers from the important program logic.

-- Paul
Jul 18 '05 #8
In article <pd************ ******@news2.no kia.com>, Olaf Meyer wrote:
Sometimes if find it clumsy unsing the following approach building strings:

cmd = "%s -start %s -end %s -dir %s" % (executable, startTime, endTime,
directory)

Especially if you have a lot of variable input it makes it hard to match
the variables to the proper fields. From other scripting languanges I'm
used to something like:

$cmd = "$executabl e -start $startTime -end $endTime -dir $directory"

This makes it very easy to see how the string is actually built. You
dont't have to worry where which variables go.

Is there a similar way to do this in python?


Go here:
http://lfw.org/python/

Look under "string interpolation for Python".

Examples supported:

"Here is a $string."
"Here is a $module.member. "
"Here is an $object.member. "
"Here is a $functioncall(w ith, arguments)."
"Here is an ${arbitrary + expression}."
"Here is an $array[3] member."
"Here is a $dictionary['member']."

Thanks to Ka-Ping Yee! I've succesfully used this to build a homebrew
templating language. It's nice and lightweight.

--
..:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
Jul 18 '05 #9

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

Similar topics

2
4354
by: Sebek | last post by:
Hello, I'm transforming a XML document in XHTML but I have problems using sub-strings, it will be clearer with an exemple: What I have: <form href="identification.php?PHPSESSID=134134&page=2&param=3" > </form> what I want:
3
343
by: Eddie | last post by:
I searched with my problem but with no results :( My question is: how can I generate string, having only simple pattern, like, midend For example tyis pattern should reproduce strings like: 1. 0min4end 2. 0min5end 3. 0min6end 4. 0min7end
7
5634
by: arkobose | last post by:
hey everyone! i have this little problem. consider the following declaration: char *array = {"wilson", "string of any size", "etc", "input"}; this is a common data structure used to store strings of any lengths into an array of pointers to char type variable. my problem is: given the declaration
6
2776
by: Dennis | last post by:
I was trying to determine the fastest way to build a byte array from components where the size of the individual components varied depending on the user's input. I tried three classes I built: (1) using redim arrays to add to a normal byte array (2) using an ArrayList and finally (3) using a memorystream. These three classes are listed below the test sub called "TestBuildByteArray". It was interesting that using the memorystream was...
14
2348
by: ranjmis | last post by:
Hi all, Below is the code wherein I am initializing double dimentional array inside main with string literals. Now I want to display the strings using a function call to which I just want to pass the array as argument with no other info like number of strings. Is there a way to achieve that?
1
5690
by: jamesd | last post by:
First off my programming experience is very limited and I haven't used C/C++ in the past 4/5 years so I'm fairly c**p at it. Basically I'm trying to write a function that opens a .wav file and store the binary version of this file in a variable named 'input'. 'input' is a x integer array. 'num' is the no. of bits in the array divided by 16 (rounded up). The following is my code: using namespace std; FILE *fp; int main(int argc,...
95
5244
by: hstagni | last post by:
Where can I find a library to created text-based windows applications? Im looking for a library that can make windows and buttons inside console.. Many old apps were make like this, i guess ____________________________________ | | | ------------------ | | | BUTTON | | | ...
17
4436
by: john | last post by:
All: I'm a long-time developer, new to PHP.... Is there an idiom used in PHP to construct SQL statments from $_POST data? I would guess that in many applications, the data read from $_POST are used to build SQL statements. Certainly, we can do the following:
0
8676
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8608
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,...
0
9164
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9029
jinu1996
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...
0
5860
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();...
0
4370
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...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2332
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2006
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.