在Python脚本中运行系统命令
我正在阅读《A byte of Python》这本书,想学习一些语法和方法等等……
我刚开始写一个简单的备份脚本(直接来自书本):
#!/usr/bin/python
# Filename: backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['"C:\\My Documents"', 'C:\\Code']
# Notice we had to use double quotes inside the string for names with spaces in it.
# 2. The backup must be stored in a main backup directory
target_dir = 'E:\\Backup' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. We use the zip command to put the files in a zip archive
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
结果,它失败了。如果我在终端里运行 zip 命令,它是可以正常工作的。我觉得失败的原因是 zip_command
这个命令实际上没有被执行。我不知道该怎么运行它。
简单地输入 zip_command
是不行的。(我正在使用 Python 3.1)
4 个回答
我建议你下一步修改你的脚本,让它打印出命令字符串,然后看看这个字符串是否看起来正确。
你还可以尝试做一个批处理文件,打印出环境变量,然后让Python去运行这个文件,看看环境变量的情况,特别是PATH变量。
下面是一个建议的例子:
set
echo Trying to run zip...
zip
把这些内容放在一个名为 C:\mytest.cmd
的批处理文件里,然后让你的Python代码去运行它:
result_code = os.system("C:\\mytest.cmd")
print('Result of running mytest was code', result_code)
如果成功,你会看到环境变量被打印出来,然后会显示“尝试运行zip...”,如果zip成功运行,它会打印出zip的版本号和如何使用它的信息。
你确定当你在命令行手动输入命令时,Python脚本能看到和你一样的环境吗?可能在Python运行这个命令的时候,zip这个工具并不在它能找到的路径上。
如果你能把代码格式化成代码的样子,那会对我们很有帮助。你只需要选中代码部分,然后点击编辑器工具栏上的“代码示例”按钮。这个按钮的图标看起来像“101/010”,如果你把鼠标放在上面,会出现一个黄色的提示框,上面写着“代码示例 <pre></pre> Ctrl+K”。
我刚试了一下,如果你把代码粘贴到StackOverflow的编辑器里,带有‘#’的行会变成粗体。所以这些粗体的行就是注释。到这里为止都很好。
你的字符串里似乎包含了反斜杠字符。你需要把每个反斜杠都加倍,比如这样:
target_dir = 'E:\\Backup'
这是因为Python对反斜杠有特殊的处理。它引入了一个“反斜杠转义”,这样你就可以在一个被引号包围的字符串里放入引号:
single_quote = '\''
你也可以使用Python的“原始字符串”,它对反斜杠的规则简单得多。原始字符串是用r"
或r'
开头,并分别用"
或'
结束。举个例子:
# both of these are legal
target_dir = r"E:\Backup"
target_dir = r'E:\Backup'