简体   繁体   English

在python脚本中运行系统命令

[英]running a system command in a python script

I have been going through "A byte of Python" to learn the syntax and methods etc... 我已经通过“ Python的一个字节”来学习语法和方法等。

I have just started with a simple backup script (straight from the book): 我刚开始使用一个简单的备份脚本(直接从书中):

#!/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')

Right, it fails. 是的,它失败了。 If I run the zip command in the terminal it works fine. 如果我在终端中运行zip命令,它将正常工作。 I think it fails because the zip_command is never actually run. 我认为它失败了,因为zip_command从未真正运行过。 And I don't know how to run it. 而且我不知道如何运行它。

Simply typing out zip_command does not work. 简单地输入zip_command无效。 (I am using python 3.1) (我正在使用python 3.1)

It would help us if you could format your code as code; 如果您可以将代码格式化为代码,将对我们有帮助; select the code parts, and click on the "Code Sample" button in the editor toolbar. 选择代码部分,然后在编辑器工具栏中单击“代码示例”按钮。 The icon looks like "101/010" and if you hold the mouse pointer over it, the yellow "tool tip" box says "Code Sample <pre></pre> Ctrl+K" 该图标看起来像“ 101/010”,如果将鼠标指针悬停在该图标上,黄色的“工具提示”框将显示“代码示例<pre> </ pre> Ctrl + K”

I just tried it, and if you paste code in to the StackOverflow editor, lines with '#' will be bold. 我刚刚尝试过,如果您将代码粘贴到StackOverflow编辑器中,则带有#号的行将为粗体。 So the bold lines are comments. 因此,粗线为注释。 So far so good. 到目前为止,一切都很好。

Your strings seem to contain backslash characters. 您的字符串似乎包含反斜杠字符。 You will need to double each backslash, like so: 您需要将每个反斜杠加倍,如下所示:

target_dir = 'E:\\Backup'

This is because Python treats the backslash specially. 这是因为Python特别对待反斜杠。 It introduces a "backslash escape", which lets you put a quote inside a quoted string: 它引入了“反斜杠转义”,可让您将引号放在带引号的字符串中:

single_quote = '\''

You could also use a Python "raw string", which has much simpler rules for a backslash. 您也可以使用Python的“原始字符串”,它的反斜杠规则要简单得多。 A raw string is introduced by r" or r' and terminated by " or ' respectively. 原始字符串由r"r'引入,并分别由"'终止。 examples: 例子:

# both of these are legal
target_dir = r"E:\Backup"
target_dir = r'E:\Backup'

Are you sure that the Python script is seeing the same environment you have access to when you enter the command manually in the shell? 您确定在外壳程序中手动输入命令时,Python脚本所看到的环境与您访问的环境相同吗? It could be that zip isn't on the path when Python launches the command. 可能是因为Python启动命令时zip不在路径中。

The next step I recommend is to modify your script to print the command string, and just look at the string and see if it seems correct. 我建议的下一步是修改脚本以打印命令字符串,然后查看该字符串,看是否正确。

Another thing you can try is to make a batch file that prints out the environment variables, and have Python run that, and see what the environment looks like. 您可以尝试做的另一件事是制作一个可以打印出环境变量的批处理文件,并让Python运行该文件,然后查看环境的外观。 Especially PATH. 特别是PATH。

Here is a suggested example: 这是一个建议的示例:

set
echo Trying to run zip...
zip

Put those in a batch file called C:\\mytest.cmd , and then have your Python code run it: 将它们放在一个名为C:\\mytest.cmd的批处理文件中,然后让您的Python代码运行它:

result_code = os.system("C:\\mytest.cmd")
print('Result of running mytest was code', result_code)

If it works, you will see the environment variables printed out, then it will echo "Trying to run zip...", then if zip runs it will print a message with the version number of zip and how to run it. 如果可行,您将看到打印出的环境变量,然后回显“试图运行zip ...”,然后如果运行zip,则会打印一条消息,其中包含zip的版本号以及运行方式。

zip命令仅适用于Linux,不适用于Windows。这就是为什么它会出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM