How to send a subprocess to the background & witho

2019-09-04 07:25发布

问题:

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?

回答1:

& 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()


回答2:

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'])