【发布时间】:2016-02-20 00:11:27
【问题描述】:
我正在尝试从 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() 相关的内容?
【问题讨论】:
标签: python linux subprocess popen