How to send a subprocess to the background & without using shell=True

I'm trying to write a part of a Python script what changes the root MySQL password under Linux for a small web-admin interface. I've followed the official MySQL documentation on changing the root password, and came up with this shell script, what works nicely:

shopt -s xpg_echo
# stopping running MySQL server
invoke-rc.d mysql stop

# creating init file in a mysqld readable location
cat > /var/lib/mysql/mysql-init <<END
UPDATE mysql.user SET Password=PASSWORD('x123') WHERE User='root';
FLUSH PRIVILEGES;
END

# running mysqld_safe with init-file in the background
mysqld_safe --init-file=/var/lib/mysql/mysql-init &

sleep 5

# stopping mysql
invoke-rc.d mysql stop

# deleting the init file
rm /var/lib/mysql/mysql-init

# starting mysql
invoke-rc.d mysql start

There is one part, where I have to start mysqld_safe and let it run for a few seconds and the stop it nicely with invoke-rc.d. In the shell script I could solve it with & and sleep 5.

My problem is that I don't know how could I do this in the Python script without using shell=True. I could do all the other parts with Popen and shlex.split(cmd), but & doesn't seem to go through either shlex.split(cmd) or through shell=False.

Is it just a simple problem with & in the command line or I really need shell=True for this? If not, do I need to use threads?

Answers


& is a shell thing, so, yes, if you want to use & to run a command in the background, you need the shell. However, you can also do this entirely in Python:

proc = subprocess.Popen(["mysqld_safe", "--init-file=/var/lib/mysql/mysql-init"])
time.sleep(5)
proc.kill()

I'm probably missing something, but wouldn't something like this work?

import time
import subprocess

p = subprocess.Popen(['mysqld_safe', '--init-file=/var/lib/mysql/mysql-init'])
time.sleep(5)
subprocess.call(['invoke-rc.d', 'mysql', 'stop'])

Need Your Help

Ruby confluence4r examples

ruby api wiki xml-rpc confluence

I cannot find where to download the confluence4r gem and it doesn't work when I do:

Inheritance with Generics

java generics inheritance tree compiler-errors

I am trying to implement a recursive tree structure with arbitrary keys in Java. Basically what I want is to have a Tree&lt;X,Y&gt; which holds an X and more (sub)Trees, indexed by a set of Ys. Ho...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.