subprocess.Popen 中的参数被忽略
Parameters are ignored in subprocess.Popen
我正在尝试从 python 脚本中 运行 一个 shell 命令。这是 CentOS linux 发行版中的 运行。 Python 版本是 2.6.6.
文件系统如下:
bash-4.1$ ls
example.py file1 file2 file3
脚本example.py如下:
#!/usr/bin/python
import os
import logging
import subprocess
import shlex
if __name__ == "__main__":
path = os.getcwd()
command = "touch file1 file2 file3"
print("Running \"{0}\" at {1}".format(command, path))
command_as_list = shlex.split(command)
print("command_as_list = {0}".format(command_as_list))
process = subprocess.Popen(command_as_list,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=path)
if process.wait() == -1:
raise Exception("Error in command {0}".format(command))
if process.stderr is not None:
print("Error ouput: {0}".format(process.stderr.read()))
运行 脚本产生以下输出:
bash-4.1$ ./example.py
Running "touch file1 file2 file3" at /home/example
command_as_list = ['touch', 'file1', 'file2', 'file3']
Error ouput: touch: missing file operand
Try `touch --help' for more information
运行 直接在命令行上的命令按预期工作:
bash-4.1$ touch file1 file2 file3
看起来 file1 file2 file3
部分被忽略了。知道为什么吗?我是否遗漏了与使用 subprocess.Open()
相关的内容?
如果将 shell 设置为 True,则不必使用 shlex - 只需将命令作为字符串传递即可。
另一种方法是删除 shell=True
。
希望对您有所帮助:)
UPD:justr 试过了 - 它应该可以解决问题。
我正在尝试从 python 脚本中 运行 一个 shell 命令。这是 CentOS linux 发行版中的 运行。 Python 版本是 2.6.6.
文件系统如下:
bash-4.1$ ls
example.py file1 file2 file3
脚本example.py如下:
#!/usr/bin/python
import os
import logging
import subprocess
import shlex
if __name__ == "__main__":
path = os.getcwd()
command = "touch file1 file2 file3"
print("Running \"{0}\" at {1}".format(command, path))
command_as_list = shlex.split(command)
print("command_as_list = {0}".format(command_as_list))
process = subprocess.Popen(command_as_list,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=path)
if process.wait() == -1:
raise Exception("Error in command {0}".format(command))
if process.stderr is not None:
print("Error ouput: {0}".format(process.stderr.read()))
运行 脚本产生以下输出:
bash-4.1$ ./example.py
Running "touch file1 file2 file3" at /home/example
command_as_list = ['touch', 'file1', 'file2', 'file3']
Error ouput: touch: missing file operand
Try `touch --help' for more information
运行 直接在命令行上的命令按预期工作:
bash-4.1$ touch file1 file2 file3
看起来 file1 file2 file3
部分被忽略了。知道为什么吗?我是否遗漏了与使用 subprocess.Open()
相关的内容?
如果将 shell 设置为 True,则不必使用 shlex - 只需将命令作为字符串传递即可。
另一种方法是删除 shell=True
。
希望对您有所帮助:)
UPD:justr 试过了 - 它应该可以解决问题。