Python script execute commands in terminal

I read this somewhere a while ago, but did not seem to find it. I try to find a command that will execute commands in the terminal and then print the result.

For example: a script would be:

command 'ls -l' 

It gives the result of executing this command in the terminal

+74
python terminal
Sep 16 '10 at 21:28
source share
9 answers

There are several ways to do this:

A simple way is to use the os module:

 import os os.system("ls -l") 

More complex things can be achieved using the subprocess module: for example:

 import subprocess test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE) output = test.communicate()[0] 
+137
Sep 16 '10 at 21:32
source share

I prefer to use the subprocess module:

 from subprocess import call call(["ls", "-l"]) 

The reason is that if you want to pass some variable to a script, this gives a very simple way, for example, to take the next part of the code

 abc = ac call(["vim", abc]) 
+22
Mar 08 '16 at 18:20
source share
  • Custom standard input for python subprocess

In fact, any question about the subprocess will be a good read

  • stack overflow
+6
Sep 16 '10 at 21:30
source share

You should also look at .getstatusoutput commands

It returns a tuple of length 2. The first is the integer return (0 - when the commands are successful); the second is the entire output, as shown in the terminal.

For ls

  import commands s=commands.getstatusoutput('ls') print s >> (0, 'file_1\nfile_2\nfile_3') s[1].split("\n") >> ['file_1', 'file_2', 'file_3'] 
+2
Mar 13 '13 at 3:08
source share

os.popen () is pretty simple to use, but it's deprecated since Python 2.6. Instead, you should use the subprocess module.

Read here: reading the os.popen command (command) in a line

+1
Apr 28 '13 at 23:26
source share
 import os os.system("echo 'hello world'") 

That should work. I do not know how to print the output to the Python shell.

+1
Feb 03 '18 at 4:43
source share

You can import the os module and use it as follows:

 import os os.system('#DesiredAction') 
0
Jan 16 '19 at 10:43
source share

Good day! My car is not a prerequisite that the problem is that I have everything I need and what I need to do to find out how the content management system (β€œMongo”) works. ) Mongo interface and its reviews, comments and comments: faire for que mon script.py Continue to create basic automation principles and script execution.

0
Jul 15 '19 at 11:44
source share

In the desktop GUI (some of you may not use it), you can scroll through the desktop shortcut and have a command in it to open the cancellation file. If you copy and paste it into your python interpreter, it should work. (I'm not sure if this will work, but why not give it a try!) Sorry for all the spelling mistakes ... I'm only 11. This information is NOT compiled! it's just me lazy making up a name! remember im only 11!

-5
Dec 31 '15 at 9:01
source share



All Articles