0

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. e.g. Command line question

Could someone, for example, explain how to achieve the following:

  1. Create a filename in python (e.g. "db_dump 2013-08-05.sql")
  2. Dump a mysql database using the mysql command line utilities (e.g. mysqldump --result-file="db_dump 2013-08-05.sql" --all-databases)
Community
  • 1
  • 1
cammil
  • 8,112
  • 14
  • 49
  • 82

3 Answers3

1

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. E.g. when you let an untrusted use specify the file name.

Hans Then
  • 10,149
  • 2
  • 30
  • 49
  • *`shell=True`* can be a security risk Yes it is and this begs a question - what did you use it for in this case? Also if you use `shell=True` then you should pass string not a list and vice versa - see http://bugs.python.org/issue7839 – Piotr Dobrogost Aug 05 '13 at 20:19
  • Is there something I need to do to get into the right directory? This still does not work for me. – cammil Aug 06 '13 at 08:20
  • Have a look at these commands: http://docs.python.org/2/library/os.html#os-file-dir, especially `os.chdir()` and `os.getcwd()`. – Hans Then Aug 06 '13 at 08:34
  • @Piotr Dobrogost the question _strongly_ suggests the use case: Make periodic dump of a database. – Hans Then Aug 06 '13 at 08:45
  • I don't see how it relates to using `shell=True`. – Piotr Dobrogost Aug 06 '13 at 08:54
  • `shell=True` is easier to try and debug. Since the question contained no reasons to assume using `shell=True` would be a security risk, I answered in the more straightforward manner. – Hans Then Aug 06 '13 at 09:07
0
  1. fname = "db_dump%s.sql"%time.strftime("%Y-%m-%d") assuming thats what you mean

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

Joran Beasley
  • 93,863
  • 11
  • 131
  • 160
0

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,

Community
  • 1
  • 1
Christian David
  • 186
  • 1
  • 3