要直接回答您的问题,请阅读以下内容。但是您的程序存在很多问题,我在“更好的实践”中介绍了其中一些问题。
默认情况下,subprocess.Popen https://docs.python.org/2/library/subprocess.html#subprocess.Popen命令以字符串列表的形式提供。
但是,您也可以使用shell
执行命令的参数“格式与在 shell 提示符下键入时完全相同”。
No:
>>> p = Popen("cat -n file1 file2")
Yes:
>>> p = Popen("cat -n file1 file2", shell=True)
>>> p = Popen(["cat", "-n", "file1", "file2"])
这两个选项之间存在许多差异,并且每个选项都有有效的用例。我不会尝试总结差异 -Popen docs https://docs.python.org/2/library/subprocess.html#subprocess.Popen在这方面已经做得非常出色了。
因此,对于您的命令,您将执行以下操作:
cmd = "gnome-terminal -x sudo git clone git://github.com/pererinha/gedit-snippet-jquery.git && sudo cp -f gedit-snippet-jquery/js.xml /usr/share/gedit/plugins/snippets/js.xml && sudo rm -rf gedit-snippet-jquery"
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT,
close_fds=False)
更好的实践
然而,使用 Python 作为许多系统命令的包装器并不是一个好主意。至少,您应该将命令分解为单独的 Popen,以便可以充分处理非零退出。事实上,这个脚本似乎更适合作为 shell 脚本。但如果你坚持使用 Python,还有更好的实践。
The os module http://docs.python.org/library/os.html应该取代调用rm
and cp
。虽然我没有这方面的经验,但你可能想看看像这样的工具GitPython http://gitorious.org/git-python与 Git 存储库交互。
兼容性问题
最后,拨打电话时应小心gnome-terminal
and sudo
。并非所有 GNU/Linux 用户都运行 Ubuntu,也不是每个人都运行 Ubuntusudo
,或安装的 GNOME 终端模拟器。在目前的形式下,如果出现以下情况,您的脚本将会崩溃,而且毫无帮助:
- The
sudo
命令未安装
- 该用户不在
sudoers
group
- 用户不使用 GNOME 或其默认终端模拟器
- 未安装 Git
如果您愿意假设您的用户正在运行 Ubuntu,请致电x-terminal-emulator
是比打电话更好的选择gnome-terminal
直接,因为它将调用他们安装的任何终端模拟器(例如xfce4-terminal
对于 Xubuntu 用户)。