简体   繁体   中英

How can I keep my program running when I use subprocess.call() to switch user?

Whenever I run this program, it completes the first function perfectly and then ends the program before doing anything else. How can I allow the other two functions to run?

import subprocess

subprocess.call(["su", "my_user"])  # runs perfectly
print("user switched to my_user")  # does not run
subprocess.call(["cd", "../documents/my_code"])  # does not run

By the way, I am running this from a Linux terminal using ipython.

This isn't doing what you think it is. When you run su , just as the function says, this runs as a subprocess. That subprocess will start as my_user and immediately exit, but your Python process is unaffected. You will still be the original user.

You can feed commands into that subprocess, assuming you need to run things as that other user, but your process isn't going to change.

Followup

subprocess.call waits for the command to finish. The su command is going to create a new shell, logged in as the new user, and that shell will present a new prompt to you. You probably thought your Python script had ended and you were back at the original prompt, but that's not the case. The prompt you're seeing is from su , and you are the new user. If you press Ctrl-D, then the su will exit, your script will continue, and you'll see your script type "user switched to my_user". Thus, you are nested several shells deep and don't realize it. ;)

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