{"id":86750,"date":"2023-02-03T10:00:37","date_gmt":"2023-02-03T04:30:37","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=86750"},"modified":"2023-02-03T10:00:37","modified_gmt":"2023-02-03T04:30:37","slug":"python-subprocess-module","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/","title":{"rendered":"Python Subprocess Module"},"content":{"rendered":"<p><span style=\"font-weight: 400\">In a computer, everything that occurs is a process, to put it simply. For example, you begin a new process each time you launch an application, issue a command-line command, or execute a Python script. Likewise, everything on your computer, from displaying a menu bar to launching a complicated application, is a process.<\/span><\/p>\n<p><span style=\"font-weight: 400\">For instance, when you run a Python script from the command line, a new process is started. There is a relationship between these two processes: the process that creates another is the parent, and the newly generated process is the child.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Similarly, a Python script can start a new process, at which point it takes on the role of the new process parent. In this post, we&#8217;ll look at how to launch various subprocesses within a standard Python script using the Python subprocess module.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Although this is a simple post, it may help to have a basic understanding of Python to follow along with the examples and concepts.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">Python Subprocess Module<\/span><\/h3>\n<p><span style=\"font-weight: 400\">A common Python module called the subprocess allows you to launch new processes within a Python script. When you need to execute numerous processes simultaneously or call an external program or command from inside your Python code, it&#8217;s beneficial and the option that is advised.<\/span><\/p>\n<p><span style=\"font-weight: 400\">The ability to manage inputs, outputs, and even errors generated by the child process from the Python code is one of the advantages of the subprocess module. In addition, this option increases the power and flexibility of calling subprocesses by allowing, for example, the use of the subprocess output as a variable throughout the remainder of the Python script.<\/span><\/p>\n<p><span style=\"font-weight: 400\">A common Python module called the subprocess allows you to launch new processes within a Python script. When you need to execute numerous processes simultaneously or call an external program or command from inside your Python code, it&#8217;s beneficial, and the option is advised.<\/span><\/p>\n<p><span style=\"font-weight: 400\">The ability to manage inputs, outputs, and even errors generated by the child process from the Python code is one of the advantages of the subprocess module. In addition, this option increases the power and flexibility of calling subprocesses by allowing, for example, the use of the subprocess output as a variable throughout the remainder of the Python script.<\/span><\/p>\n<p><b>Use of subprocess.run() in Python<\/b><\/p>\n<p><span style=\"font-weight: 400\">It&#8217;s easy to run commands in the background with Python&#8217;s run function using the subprocess module rather than worrying about starting a new terminal or typing the command by hand. Using this function to automate processes or run commands you don&#8217;t want to carry out manually is also an excellent idea.<\/span><\/p>\n<p><span style=\"font-weight: 400\">The iterable *args, which contains the instructions to run the subprocess, is the significant parameter given to the function. In addition, the paths to the Python executable and the Python script should be included in the args to execute other Python code.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Thus, it would appear as follows:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import subprocess\nsubprocess.run([\"python\", \"TechVidvan.py\"])\n<\/pre>\n<p><span style=\"font-weight: 400\">Instead of supplying a .py file, Python code can alternatively be directly entered into the procedure. An example of using such a subprocess is as follows:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">result = subprocess.run([\"\/usr\/local\/bin\/python\", \"-c\", \"print('Subprocess with TechVidvan')\"])\n<\/pre>\n<p><span style=\"font-weight: 400\">We have the following in args:<\/span><\/p>\n<p><span style=\"font-weight: 400\">Python&#8217;s local executable can be found at &#8220;\/usr\/local\/bin\/python&#8221; in the path.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Python&#8217;s &#8220;-c&#8221; tag enables users to enter Python code as text on the command line.<\/span><\/p>\n<p><span style=\"font-weight: 400\">The actual code to be executed is &#8220;print(&#8216;Subprocess with TechVidvan&#8217;)&#8221;.<\/span><\/p>\n<p><span style=\"font-weight: 400\">This is equivalent to running the command line with the argument \/usr\/local\/bin\/python -c print(&#8216;Subprocess with TechVidvan&#8217;). This structure will be used for most of the code in this article because it makes it simpler to demonstrate the run function&#8217;s features. But, of course, you could always call another Python script that uses the same code.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Additionally, the first string in args in both of the cases above where we used the run function refers to the location of the Python executable. We&#8217;ll maintain the generic path used in the first example for the rest of the essay.<\/span><\/p>\n<p><span style=\"font-weight: 400\">The sys module can help you if you&#8217;re having problems determining the location of the Python executable on your computer. This module works well with the subprocess, and a good application for it is to change the executable&#8217;s path to look like this:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import sys\n\nresult = subprocess.run([sys.executable, \"-c\", \"print('Subprocess with TechVidvan')\"])\n<\/pre>\n<p><span style=\"font-weight: 400\">The completed process is represented by an object of the CompletedProcess class, which the run function then returns.<\/span><\/p>\n<p><span style=\"font-weight: 400\">If we print the results, they will appear as follows:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">CompletedProcess(args=['\/usr\/bin\/python3', '-c', \"print('Subprocess with TechVidvan')\"], returncode=0)<\/pre>\n<p><span style=\"font-weight: 400\">As we would anticipate, a CompletedProcess class instance displays the command and the returncode=0, signifying that it was executed correctly.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">Parameters For Subprocess Module<\/span><\/h3>\n<p><span style=\"font-weight: 400\">We should look into options that allow us to use the run function better now that we know how to launch a subprocess.<\/span><\/p>\n<h3>Controlling the Result in Subprocess Module<\/h3>\n<p><span style=\"font-weight: 400\">Remember that the object returned by the aforementioned function displays the command and the return code with no more details regarding the subprocess. The user has more control over their code if the capture output argument is set to True, which returns more data.<\/span><\/p>\n<p><b>Input:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">result = subprocess.run([\"python\", \"-c\", \"print('Subprocess with TechVidvan')\"], capture_output=True)\n<\/pre>\n<p><b>Output:<\/b><\/p>\n<div class=\"code-output\">CompletedProcess(args=[&#8216;\/usr\/bin\/python3&#8217;, &#8216;-c&#8217;, &#8220;print(&#8216;Subprocess with TechVidvan&#8217;)&#8221;], returncode=0, stdout=b&#8217;Subprocess with TechVidvan\\n&#8217;, stderr=b&#8221;)<\/div>\n<p><span style=\"font-weight: 400\">Both are byte sequences representing the outputs of the respective subprocess. To have these outputs as strings, we can, alternatively, set the text argument to True.<\/span><\/p>\n<p><span style=\"font-weight: 400\">However, if your script makes a mistake, stderr will have the following error message, and stdout will be empty:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">result = subprocess.run([\"python\", \"-c\", \"print(subprocess)\"], capture_output=True, text=True)\nprint('output: ', result.stdout)\nprint('error: ', result.stderr)\n<\/pre>\n<p><span style=\"font-weight: 400\"><strong>Output<\/strong>:<\/span><\/p>\n<div class=\"code-output\">error: Traceback (most recent call last): File &#8220;&lt;string&gt;&#8221;, line 1, in &lt;module&gt; NameError: name &#8216;subprocess&#8217; is not defined<\/div>\n<p><span style=\"font-weight: 400\">You can now use the subprocesses&#8217; output as a conditional variable for the rest of your code, a constant variable, or even to keep track of the subprocesses and save them (assuming all are completed without issues) and their outputs.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">The Input in the Subprocess Module<\/span><\/h3>\n<p><span style=\"font-weight: 400\">As we previously saw, it is possible to use a child process&#8217; output throughout the rest of the parent code. However, the contrary is also true: by utilizing the input parameter, we may send a value from the parent process to the child process.<\/span><\/p>\n<p><span style=\"font-weight: 400\">If text=True, we utilize this argument to communicate any string or byte sequences to the subprocess, which will receive this data via the sys module. The input parameter will be read by the sys.stdin.read() function in the child process, where it can then be assigned to a variable and utilized in the code like any other variable.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here&#8217;s an example:<\/span><\/p>\n<p><b>Input:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">result = subprocess.run([\"python\", \"-c\", \"import sys; my_input=sys.stdin.read(); print(my_input)\"], capture_output=True, text=True, input='TechVidvan')\nprint(result.stdout)\n<\/pre>\n<p><b>Output:<\/b><\/p>\n<div class=\"code-output\">TechVidvan<\/div>\n<p><span style=\"font-weight: 400\">The code in the subprocess above imports the module, assigns the input to a variable using sys.stdin.read(), and outputs that variable.<\/span><\/p>\n<p><span style=\"font-weight: 400\">However, we can also input data using args and read them inside the child code using sys.argv. Let&#8217;s take the following code from a script called my script.py as an example:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import sys\n\nmy_input = sys.argv\n\ndef sum_two_values(a=int(my_input[1]), b=int(my_input[2])):\n    return a + b\n\nif __name__==\"__main__\":\n    print(sum_two_values())\n\n<\/pre>\n<p><span style=\"font-weight: 400\">The run function below contains two additional values that will be retrieved by sys.argv and added to my script.py. They are contained in the script that will serve as the parent process for the child process above.<\/span><\/p>\n<p><b>Input:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">result = subprocess.run([\"python\", \"my_script.py\", \"2\", \"4\"], capture_output=True, text=True)\nprint(result.stdout)\n<\/pre>\n<p><b>Output:<\/b><\/p>\n<p>6<\/p>\n<h3><span style=\"font-weight: 400\">Conclusion:<\/span><\/h3>\n<p><span style=\"font-weight: 400\">A sub-process is an artificially produced computer process. Tools like task manager and htop allow us to monitor the active processes on our computer. In addition, Python&#8217;s subprocess library is available. Currently, the run function provides a straightforward interface for setting up and controlling subprocesses.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Because we connect directly with the OS, we can construct any application with them. Finally, remember that creating something you would like to use is the best way to learn.<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In a computer, everything that occurs is a process, to put it simply. For example, you begin a new process each time you launch an application, issue a command-line command, or execute a Python&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":86968,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[4834],"class_list":["post-86750","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python-subprocess-module"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Subprocess Module - TechVidvan<\/title>\n<meta name=\"description\" content=\"A sub-process is an artificially produced computer process. Learn about Python subprocess module and its parameters with examples.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Subprocess Module - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"A sub-process is an artificially produced computer process. Learn about Python subprocess module and its parameters with examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-02-03T04:30:37+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/python-subprocess-module.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Subprocess Module - TechVidvan","description":"A sub-process is an artificially produced computer process. Learn about Python subprocess module and its parameters with examples.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/","og_locale":"en_US","og_type":"article","og_title":"Python Subprocess Module - TechVidvan","og_description":"A sub-process is an artificially produced computer process. Learn about Python subprocess module and its parameters with examples.","og_url":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-02-03T04:30:37+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/python-subprocess-module.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Python Subprocess Module","datePublished":"2023-02-03T04:30:37+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/"},"wordCount":1252,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/python-subprocess-module.webp","keywords":["Python Subprocess Module"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/","url":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/","name":"Python Subprocess Module - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/python-subprocess-module.webp","datePublished":"2023-02-03T04:30:37+00:00","description":"A sub-process is an artificially produced computer process. Learn about Python subprocess module and its parameters with examples.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/python-subprocess-module.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/python-subprocess-module.webp","width":1200,"height":628,"caption":"python subprocess module"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-subprocess-module\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Python Subprocess Module"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/86750","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=86750"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/86750\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/86968"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=86750"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=86750"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=86750"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}