简体   繁体   English

有没有一种简单的方法可以在Windows中从python内部执行命令行语句?

[英]Is there a simple method for executing command line statements, in windows, from within python?

I've searched high and low for a simple explanation of how to execute command line, in windows, from within python. 我在上下搜索了有关如何在Windows中从python内部执行命令行的简单说明。

The subprocess package seems to be the answer, but I do not appear to be sufficiently experienced to make head nor tail of it. 子流程包似乎是答案,但是我似乎没有足够的经验来做文章的开头或结尾。

Some questions I have reviewed to no avail, through lack of windows focus, or through lack of examples and expected outputs. 由于缺乏Windows焦点,或者缺乏示例和预期的输出,我已经复习了一些无济于事的问题。 eg Command line question 例如命令行问题

Could someone, for example, explain how to achieve the following: 例如,有人可以解释如何实现以下目标:

  1. Create a filename in python (eg "db_dump 2013-08-05.sql" ) 在python中创建文件名(例如"db_dump 2013-08-05.sql"
  2. Dump a mysql database using the mysql command line utilities (eg mysqldump --result-file="db_dump 2013-08-05.sql" --all-databases ) 使用mysql命令行实用程序转储mysql数据库(例如mysqldump --result-file="db_dump 2013-08-05.sql" --all-databases

Something like this? 像这样吗

from subprocess import call
call('mysqldump --result-file="db_dump 2013-08-05.sql" --all-databases', shell=True)

Just remember, shell=True can be a security risk if you work with untrusted user supplied parameters. 请记住,如果您使用不受信任的用户提供的参数, shell=True可能会带来安全风险。 Eg when you let an untrusted use specify the file name. 例如,当您让不受信任的用户使用时,请指定文件名。

  1. fname = "db_dump%s.sql"%time.strftime("%Y-%m-%d")假设这就是您的意思

  2. os.system("mysqldump --result-file=\\"%s\\" --all-databases"%fname)

You could try Fabric, especially the "local()" command: 您可以尝试使用Fabric,尤其是“ local()”命令:

http://docs.fabfile.org/en/1.7/api/core/operations.html?highlight=local#fabric.operations.local http://docs.fabfile.org/en/1.7/api/core/operations.html?highlight=local#fabric.operations.local

in your python code you can use it like this 在您的python代码中,您可以像这样使用它

local('mysqldump ...')

Fabric is typically used from a shell (using the "fab" command and a fabfile.py containing the python code to execute). 通常从外壳程序使用Fabric(使用“ fab”命令和包含要执行的python代码的fabfile.py)。 To include it in another python script check this (first answer): 要将其包含在另一个python脚本中,请检查以下内容(第一个答案):

Launch Fab File inside a python script 在python脚本中启动Fab File

Regards, 问候,

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

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