{"id":5205,"date":"2020-04-28T10:20:05","date_gmt":"2020-04-28T10:20:05","guid":{"rendered":"https:\/\/www.askpython.com\/?p=5205"},"modified":"2023-02-16T19:57:06","modified_gmt":"2023-02-16T19:57:06","slug":"python-system-command","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/python-system-command","title":{"rendered":"Python System Command: How to Execute Shell Commands in Python?"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Introduction<\/h2>\n\n\n\n<p>Today in this tutorial, we are going to discuss <strong>how we can execute shell commands using Python system command<\/strong>.<\/p>\n\n\n\n<p>So let&#8217;s get started with some basics of Python system command.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is Python System Command?<\/h2>\n\n\n\n<p>We may need to integrate features for carrying out some system administration tasks in Python. These include finding files, running some shell commands, doing some advanced file handling, etc. And to do so, we need some way to interface between the system and the python interpreter. <\/p>\n\n\n\n<p>Executing <strong>command lines<\/strong> using Python can be easily done using some system methods from the <code>os module<\/code>. <\/p>\n\n\n\n<p>But with the introduction of the <code>subprocess<\/code> module(intending to replace some older modules), accessing command line has been a lot more easier to use. As well as to manipulate the output and avoid some limitations of the traditional methods.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Executing Shell Commands in Python<\/h2>\n\n\n\n<p>Now that we got to know about the System Commands in Python. Let us take a look into how we can implement the same.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">1. Using os.system() Method<\/h2>\n\n\n\n<p>As stated earlier, executing shell commands in Python can be easily done using some methods of the <code>os<\/code> module. Here, we are going to use the widely used <code>os.system()<\/code> method. <\/p>\n\n\n\n<p>This function is implemented using the <strong>C<\/strong> <code>system()<\/code> function, and hence has the same limitations.<\/p>\n\n\n\n<p>The method takes the system command as string in input and returns the <strong>exit code<\/strong> back.<\/p>\n\n\n\n<p>In the example below, we try to check our system <strong>Python version<\/strong> using command line in Python.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport os\n\ncommand = &quot;python --version&quot; #command to be executed\n\nres = os.system(command)\n#the method returns the exit status\n\nprint(&quot;Returned Value: &quot;, res)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nPython 3.7.4\nReturned Value:  0\n<\/pre><\/div>\n\n\n<p>Here, <code>res<\/code> stores the returned value (exit code=<strong>0<\/strong> for success). It is clear from the output, that the command is executed successfully and we get our Python version as expected.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">2. Using the subprocess Module<\/h2>\n\n\n\n<p>The <code>subprocess<\/code> module comes with various useful methods or functions to spawn new processes, connect to their input\/output\/error pipes, and obtain their return codes. <\/p>\n\n\n\n<p>In this tutorial, we are considering the <code>call()<\/code> and <code>check_output()<\/code> methods as they are <strong>easy to use<\/strong> and <strong>reliable<\/strong>. But for more info you can always refer to the <a href=\"https:\/\/docs.python.org\/3\/library\/subprocess.html\" class=\"rank-math-link\" target=\"_blank\" rel=\"noopener\">official documentation<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2.1. The call() Method<\/h3>\n\n\n\n<p>Now getting to the <code>subprocess.call()<\/code> method.<\/p>\n\n\n\n<p>The <code>call()<\/code> method takes in command line arguments passed as a list of strings or with the <strong>shell<\/strong> argument set to <code>True<\/code>. And returns back us the <strong>exit code<\/strong> or <strong>status<\/strong>.<\/p>\n\n\n\n<p>In the below code snippet, we try to install <a href=\"https:\/\/www.askpython.com\/python-modules\/pandas\/python-pandas-module-tutorial\" class=\"rank-math-link\">pandas<\/a> using <strong>PIP<\/strong> from <strong>shell<\/strong>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport subprocess\n\ncommand = &quot;pip install pandas&quot; #command to be executed\n\nres = subprocess.call(command, shell = True)\n#the method returns the exit code\n\nprint(&quot;Returned Value: &quot;, res)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nCollecting pandas\n  Downloading pandas-1.0.3-cp37-cp37m-win32.whl (7.5 MB)\nRequirement already satisfied: pytz&gt;=2017.2 in c:\\users\\sneha\\appdata\\local\\programs\\python\\python37-32\\lib\\site-packages (from pandas) (2019.3)\nRequirement already satisfied: numpy&gt;=1.13.3 in c:\\users\\sneha\\appdata\\local\\programs\\python\\python37-32\\lib\\site-packages (from pandas) (1.18.1)\nRequirement already satisfied: python-dateutil&gt;=2.6.1 in c:\\users\\sneha\\appdata\\local\\programs\\python\\python37-32\\lib\\site-packages (from pandas) (2.8.1)\nRequirement already satisfied: six&gt;=1.5 in c:\\users\\sneha\\appdata\\local\\programs\\python\\python37-32\\lib\\site-packages (from python-dateutil&gt;=2.6.1-&gt;pandas) (1.14.0)\nInstalling collected packages: pandas\nSuccessfully installed pandas-1.0.3\nReturned Value:  0\n<\/pre><\/div>\n\n\n<p>As we can see, the command is executed successfully with return value <code>zero<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2.2. The check_output() Method<\/h3>\n\n\n\n<p>The above mentioned methods execute the shell command passed successfully but don&#8217;t give the user the freedom to manipulate the way we get the output. For doing that, the <strong>subprocess&#8217;s<\/strong> <code>check_output()<\/code> method has to come into the picture.<\/p>\n\n\n\n<p>The method executes the passed <strong>command<\/strong> but instead of returning the exit status, this time it returns a <code>bytes<\/code> object. <\/p>\n\n\n\n<p>Take a closer look at the example below where we try to install the <code>pymysql<\/code> module again(already installed).<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport subprocess\n\ncommand = &quot;pip install pymysql&quot; #command to be executed\n\nres = subprocess.check_output(command) #system command\n\nprint(&quot;Return type: &quot;, type(res)) #type of the value returned\n\nprint(&quot;Decoded string: &quot;, res.decode(&quot;utf-8&quot;)) #decoded result\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nReturn type:  &lt;class &#039;bytes&#039;&gt;\nDecoded string:  Requirement already satisfied: pymysql in c:\\users\\sneha\\appdata\\local\\programs\\python\\python37-32\\lib\\site-packages (0.9.3)\n<\/pre><\/div>\n\n\n<p>Here similar to the previous cases, <code>res<\/code> holds the returned object by the <code>check_output()<\/code> method. We can see <code>type(res)<\/code> confirms that the object is of <code>bytes<\/code> type. <\/p>\n\n\n\n<p>After that, we print the <strong>decoded<\/strong> string and see that the command was successfully executed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>So, today we learned how we can <strong>execute system commands using Python system command (os.system()) and the subprocess module.<\/strong> We have considered some more python related commands here, but it is worth noting that the methods are not limited to these. <\/p>\n\n\n\n<p>We recommend trying out other commands using the above methods on your own to get a better understanding.<\/p>\n\n\n\n<p>For any further questions, feel free to comment below.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a aria-label=\"Python subprocess Documentation (opens in a new tab)\" rel=\"noreferrer noopener\" href=\"https:\/\/docs.python.org\/3\/library\/subprocess.html#module-subprocess\" target=\"_blank\" class=\"rank-math-link\">Python subprocess Documentation<\/a><\/li><li><a aria-label=\"Python os Documentation (opens in a new tab)\" rel=\"noreferrer noopener\" href=\"https:\/\/docs.python.org\/3\/library\/os.html?highlight=os%20system#os.system\" target=\"_blank\" class=\"rank-math-link\">Python os Documentation<\/a>,<\/li><li>Python System Command \u2013 os.system(), subprocess.call() &#8211; Article on Journal Dev<\/li><\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Today in this tutorial, we are going to discuss how we can execute shell commands using Python system command. So let&#8217;s get started with some basics of Python system command. What is Python System Command? We may need to integrate features for carrying out some system administration tasks in Python. These include finding files, [&hellip;]<\/p>\n","protected":false},"author":10,"featured_media":5209,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-5205","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-modules"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/5205","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/10"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=5205"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/5205\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/5209"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=5205"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=5205"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=5205"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}