简体   繁体   中英

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.

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. 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" )
  2. Dump a mysql database using the mysql command line utilities (eg 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. 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:

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

local('mysqldump ...')

Fabric is typically used from a shell (using the "fab" command and a fabfile.py containing the python code to execute). To include it in another python script check this (first answer):

Launch Fab File inside a python script

Regards,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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