better way for ' '.join(args) + '\n'?

Prasad, Ramit ramit.prasad at jpmorgan.com
Mon Oct 29 18:28:52 EDT 2012


Thomas Rachel wrote:
> Am 26.10.2012 09:49 schrieb Ulrich Eckhardt:
> > Hi!
> >
> > General advise when assembling strings is to not concatenate them
> > repeatedly but instead use string's join() function, because it avoids
> > repeated reallocations and is at least as expressive as any alternative.
> >
> > What I have now is a case where I'm assembling lines of text for driving
> > a program with a commandline interface.
> 
> Stop.
> 
> In this case, you think too complicated.
> 
> Just do
> 
>      subprocess.Popen(['prog', 'foo', 'bar', 'baz'])
> 
> -  is the most safest thing for this use case.
> 
> If it should not be possible for any reason, you should be aware of any
> traps you could catch - e.g., if you want to feed your string to a
> Bourne shell, you should escape the strings properly.
> 
> In such cases, I use
> 
> 
> def shellquote(*strs):
> 	r"""Input: file names, output: ''-enclosed strings where every ' is
> replaced with '\''. Intended for usage with the shell."""
> 	# just take over everything except ';
> 	# replace ' with '\''
> 	# The shell sees ''' as ''\'''\'''\'''. Ugly, but works.
> 	return " ".join([
> 		"'"+st.replace("'","'\\''")+"'"
> 		for st in strs
> 	])
> 
> 
> so I can use
> 
> shellquote('program name', 'argu"ment 1', '$arg 2',
>      "even args containing a ' are ok")
> 
> For Windows, you'll have to modify this somehow.
> 

The subprocess module suggests using pipes.quote for escaping.

>>> a
('program name', 'argu"ment 1', '$arg 2', "even args containing a ' are ok")
>>> import pipes
>>> map(pipes.quote, a)
["'program name'", '\'argu"ment 1\'', "'$arg 2'", '\'even args containing a \'"\'"\' are ok\'']
>>> ' '.join(a)
'\'program name\' \'argu"ment 1\' \'$arg 2\' \'even args containing a \'\\\'\' are ok\''


Ramit Prasad


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  



More information about the Python-list mailing list