python - 子进程调用

标签 python subprocess

我是 subprocess.call 函数的新手,我尝试了同一调用的不同组合,但它不起作用。

我正在尝试执行以下命令:

cmd = 'sort -k1,1 -k4,4n -k5,5n '+outpath+fnametempout+' > '+outpath+fnameout
print cmd

如果我尝试调用我会得到一个错误:

cmd = cmd.split(" ")
print cmd
subprocess.call(cmd)

我得到的错误是:

sort: stat failed: >: No such file or directory

最佳答案

这样做,您需要 shell=True 以允许 shell 重定向工作。

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

更好的方法是:

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

这避免了一起生成 shell,并且可以免受 shell 注入(inject)类型的攻击。在这里,cmd 是您原来的列表,例如

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

还应该指出,python 具有非常好的排序功能,因此我怀疑是否真的有必要通过子进程将工作传递给 sort


最后,与其使用 str.split 从字符串中拆分参数,不如使用 shlex.split 更好,因为它可以正确处理引用的字符串。

>>> 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']

关于python - 子进程调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14386775/

相关文章:

Python - 编译后有两个进程?

python - Flask-Security 的自定义身份验证方法

python - 如何终止Python Popen创建的进程

python - 将列表写入 HDFS 上的文件

python - 在 Python 中,以 currentThread() 为键的字典会导致内存泄漏吗?

python - 根据其 CA 验证 CRL

python - 添加到而不是覆盖模板 block

python - 如果作为 Python 子进程调用,多线程 Perl 脚本会导致管道损坏

python - 为什么 shell=True 和 shell=False 做同样的事情?

python - 将子进程 stderr 重定向到 stdout