Moshe Vayner
Moshe Vayner

Reputation: 798

Python String Format not working as expected when ran in a script

I creating a python script, which one of its functions is to run a shell command. When using the REPL to format the string that builds the command, it works as expected. However, when running it in the script function itself, the formatting gets messed up! Has anyone come across this issue and knows why is it happening? For the example below, I've switched the command execution to a simple print method, so I'll be able to get the immediate outcome of the formatting. Details below:

variables:

function:

def get_rifs_status():
    for rifs in rifs_names:
        print 'mco shell run -I {0} "sc qc {1} 5000"'.format(server_name, rifs)

REPL output (Good):

mco shell run -I <server_name> "sc qc <rifs> 5000"
mco shell run -I <server_name> "sc qc <rifs> 5000"

Script output (Messed-up):

 5000"ell run -I <server_name> "sc qc <rifs>
 5000"ell run -I <server_name> "sc qc <rifs>

I've tried endless options of formatting, nothing works.. I'm really going crazy here, any help would be appreciated.

Here are the details about my python env, just in case it's needed:

Python 2.6.6 (r266:84292, Jun 18 2012, 14:18:47) 
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2

Upvotes: 1

Views: 375

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123450

Your rifs values include a carriage return character, \r, putting the 'write position' back at the start of the line, so the 5000" part is written there.

Strip this character:

print 'mco shell run -I {0} "sc qc {1} 5000"'.format(server_name, rifs.rstrip('\r'))

Demo:

>>> server_name = '<server_name>'
>>> rifs = '<rifs>\r'
>>> print 'mco shell run -I {0} "sc qc {1} 5000"'.format(server_name, rifs)
 5000"ell run -I <server_name> "sc qc <rifs>
>>> print 'mco shell run -I {0} "sc qc {1} 5000"'.format(server_name, rifs.rstrip('\r'))
mco shell run -I <server_name> "sc qc <rifs> 5000"

Upvotes: 5

Related Questions