subprocess.call

前端 未结 3 829
慢半拍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:05

    it is not to compecated execute above command in python:

    import subprocess
    import sys
    proc = subprocess.Popen(['sort','-k1','1', '-k4','4n', '-k5','5n',    '+outpath+fnametempout+', '>', '+outpath+fnameout'],stdin=subprocess.PIPE)
    proc.communicate()
    
    0 讨论(0)
  • 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']
    
    0 讨论(0)
  • 2020-12-10 22:16

    example:

    subprocess.call(['ps','aux'])
    lines=subprocess.check_output(['ls','-al'])
    line_list = lines.split('\n')
    
    or
    
    handle = subprocess.Popen('ls',stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)
    handle.stdout.read()
    
    0 讨论(0)
提交回复
热议问题