代码之家  ›  专栏  ›  技术社区  ›  rodee

如何在Python中向run()传递空格分隔的参数

  •  0
  • rodee  · 技术社区  · 7 年前
    >>> from subprocess import PIPE,run
    >>> cmd="ls"
    >>> args="-l -r -t"
    >>> run([cmd,args])
    ls: invalid option -- ' '
    Try 'ls --help' for more information.
    CompletedProcess(args=['ls', '-l -r -t'], returncode=2)
    
    >>> args='-l'
    >>> run([cmd,args]) #Now works
    
    >>> args='-l'
    >>> args2='-r'
    >>> run([cmd,args,args2]) #Works too.
    

    我用剧本代替 ls -l -r -t ,我看到脚本抛出了类似的错误。

    我在一个变量中得到参数并且可能有空格,它必须按原样传递给脚本,我该怎么做?

    1 回复  |  直到 7 年前
        1
  •  1
  •   abarnert    7 年前

    假设 run subprocess.run shell=True ,命令行字符串无论哪种方式,列表或字符串都必须包含可执行文件。

    通常,正确的方法是首先使用列表:

    cmd = 'ls'
    args = [cmd, '-l', '-r', '-t']
    run(args)
    

    在这种情况下,您需要使用 shlex 把争论分开。

    你会想写一个能帮你处理事情的包装。而不是 from subprocess import run ,只是 import subprocess

    def run(cmd, argstring, *args, **kwargs):
        cmdargs = [cmd] + shlex.split(argstring)
        return subprocess.run(cmdargs, *args, **kwargs)
    

    但是,在这种情况下,您可能需要研究使用更高级的Python交互式解释器,比如IPython/Jupyter,或者使用PyPI之外的一个奇特的shell包装库,或者两者都使用。

    例如,使用 shell (这是我以前从未用过的,但在一次搜索中出现,看起来很漂亮):

    >>> from shell import shell
    >>> cmd = shell('ls -l -r -t')
    >>> print(cmd.output())
    ['total 11040',
     'drwxr-xr-x@   9 andrewbarnert  staff      288 Oct 26  2009 python-0.9.1',
    # ...
    

    In  [1]: !ls -l -r -t
    total 11040
    drwxr-xr-x@   9 andrewbarnert  staff      288 Oct 26  2009 python-0.9.1
    # ...
    

    (如果您想捕获该输出而不是仅仅看到它,那么可以阅读IPython%magic命令。)