Python:使用 shell=False 的子进程调用不起作用

2022-01-18 00:00:00 python shell subprocess

问题描述

我正在使用 Python 脚本来调用 Java 虚拟机.以下命令有效:

I am using Python script to invoke a Java virtual machine. The following command works:

subprocess.call(["./rvm"], shell=False)  # works
subprocess.call(["./rvm xyz"], shell=True) # works

但是,

subprocess.call(["./rvm xyz"], shell=False) # not working

不起作用.Python 文档 建议避免 shell=True.

does not work. Python documentation advices to avoid shell=True.


解决方案

您需要将命令拆分成单独的字符串:

You need to split the commands into separate strings:

subprocess.call(["./rvm", "xyz"], shell=False)

shell=True 时字符串会起作用,但当 shell=False

A string will work when shell=True but you need a list of args when shell=False

shlex 模块对于更复杂的命令和处理输入更有用,但很好学关于:

The shlex module is useful more so for more complicated commands and dealing with input but good to learn about:

import shlex

cmd = "python  foo.py"
subprocess.call(shlex.split(cmd), shell=False)

shlex tut

相关文章