Tags: 3currently, build, concatenation, files, lists, ossystem, output, process, programming, python, statements, string

Using os.system() and string concatenation

On Programmer » Python

2,547 words with 1 Comments; publish: Wed, 26 Dec 2007 23:51:00 GMT; (200140.63, « »)

Using Python 2.3

Currently I process three files and build the output of those files in

to lists using for statements.

I think take those lists and provide them to an os.system() call.

cmd = "/usr/sbin/useradd"

os.system(cmd + list1[0] + list1[1] + list2[0] + list3[0])

This executes without any errors, but doesn't execute the command

supplied to os.system(). Now if I place them all in cmd first, then

supply it to os.system() it executes just fine. So there really isn't

a problem, just wanting to know what would cause such behavior.

Thanks,

Wayne

All Comments

Leave a comment...

  • 1 Comments
    • In article <mailman.4764.1097606614.5135.python-list.python.todaysummary.com.python.org>,

      Wayne Witzel III <wwitzel3.python.todaysummary.com.gmail.com> wrote:

      > Using Python 2.3

      > Currently I process three files and build the output of those files in

      > to lists using for statements.

      > I think take those lists and provide them to an os.system() call.

      > cmd = "/usr/sbin/useradd"

      > os.system(cmd + list1[0] + list1[1] + list2[0] + list3[0])

      > This executes without any errors, but doesn't execute the command

      > supplied to os.system(). Now if I place them all in cmd first, then

      > supply it to os.system() it executes just fine. So there really isn't

      > a problem, just wanting to know what would cause such behavior.

      As already mentioned in other followups, could be white

      space missing.

      On the other hand, this looks to me like a very good place to

      use os.spawnv instead of os.system. It might resolve the

      present problem, but much more importantly, it will avoid

      more dangerous problems of a similar nature. When you construct

      a shell command out of data from files, data becomes shell

      syntax, and there is in theory the possibility that the result

      will be worse than just invalid, it may execute a different

      command or different parameters than you had in mind, with a

      wide range of potentially unpleasant results.

      But spawnv() executes the command directly, with the parameters

      you supply, unlike system() which invokes the shell. So with

      spawnv() you don't need white space, but more importantly the

      only command that can run as a result is the one you specify.

      os.spawnv(os.P_WAIT, '/usr/sbin/useradd',

      ['useradd', list1[0], list1[1], list2[0], list3[0]])

      Donn Cave, donn.python.todaysummary.com.u.washington.edu

      #1; Wed, 26 Dec 2007 23:52:00 GMT