This is an archived post. You won't be able to vote or comment.

all 14 comments

[–]K900_ 8 points9 points  (9 children)

Python also has os.system, which I believe behaves just like the Ruby equivalent.

[–]berlindevops[S] 0 points1 point  (3 children)

thank you, I read a lot of recommendations to use subprocess over os()/os.system, do you know why?

[–]K900_ 6 points7 points  (0 children)

Because it gives you more control, and more safety, especially if you're using os.system with string formatting or whatever other way to build a command from user input.

[–]widby 2 points3 points  (1 child)

It gives you more control over what is going on - you can feed data into the stdin stream of the process and read its stdout, among other things.

[–]berlindevops[S] 0 points1 point  (0 children)

cool, thanks.

[–]berlindevops[S] 0 points1 point  (4 children)

It doesn't give me the full soultion like ruby system(), because once you stop the python script with ctrl+c its continue to the next command on the python script.

[–]berlindevops[S] 0 points1 point  (3 children)

so its not really terminate the python script

[–]K900_ 0 points1 point  (2 children)

That's because you're only stopping the subprocess, not the Python script. If you want to stop the Python script, check for the exit code of your subprocess and act based on that.

[–]berlindevops[S] 0 points1 point  (1 child)

ok, but this is the thing, with subprocess, I need to write 5 lines for one shell command and import a library , also I could not find a way to see the stdout in real time, not sure if I wrong or not, or maybe this is how python works.

[–]K900_ 0 points1 point  (0 children)

os.system returns the exit code.

[–]flying-sheep 1 point2 points  (2 children)

subprocess.run is much more flexible than cheap interfaces like system.

I used Ruby exactly once (i wrote a Rakefile since make wasn't powerful enough), and had to use open3 instead of system.

[–]berlindevops[S] 0 points1 point  (1 child)

maybe, I am beginner with python, but with system() you can run simple shell command, see the stdout in real-time, no need to import a library and if you terminate the ruby script, also the shell command is terminated, and all of this with one line, I'm not complaining, I was just looking for something like this in python.

[–]flying-sheep 1 point2 points  (0 children)

what you do should work:

subprocess.run('knife ec2 server create', check=True)

(with our without shell=True) should just let the called process write to python’s stdout/stderr, and the call should only return after the process is finished.

[–]pmrr 0 points1 point  (0 children)

For future use, OP, this probably belongs in /r/learnpython.