subprocess.call

前端 未结 3 830
慢半拍i
慢半拍i 2020-12-10 21:48

I am new to the subprocess.call function and I have tried different combinations of the same call but it is not working.

I am trying to execute the following command

3条回答
  •  眼角桃花
    2020-12-10 22:09

    Doing it this way, you need shell=True to allow the shell redirection to work.

    subprocess.call('sort -k1,1 -k4,4n -k5,5n '+outpath+fnametempout,shell=True)
    

    A better way is:

    with open(outpath+fnameout,'w') as fout: #context manager is OK since `call` blocks :)
        subprocess.call(cmd,stdout=fout)
    

    which avoids spawning a shell all-together and is safe from shell injection type attacks. Here, cmd is a list as in your original, e.g.

    cmd = 'sort -k1,1 -k4,4n -k5,5n '+outpath+fnametempout
    cmd = cmd.split()
    

    It should also be stated that python has really nice sorting facilities and so I doubt that it is actually necessary to pass the job off to sort via a subprocess.


    Finally, rather than using str.split to split the arguments, from a string, it's probably better to use shlex.split as that will properly handle quoted strings.

    >>> import shlex
    >>> cmd = "foo -b -c 'arg in quotes'"
    >>> print cmd.split()
    ['foo', '-b', '-c', "'arg", 'in', "quotes'"]
    >>> print shlex.split(cmd)
    ['foo', '-b', '-c', 'arg in quotes']
    

提交回复
热议问题