title: How to Run Python Script (Scrapy) From Ktor
body: <p><strong>What I'm trying to do:</strong></p>
  <ol>
  <li><p>Android Application (ADMIN) that gets job Title from user and fetches all the jobs related to it using Scrapy (Python) which are saved to database through API.</p>
  </li>
  <li><p>Android Application (CLIENT) that fetches all the data from database through API.</p>
  </li>
  </ol>
  <p><strong>Problem:</strong>
  I'm stuck on how to connect my python Script with Ktor.</p>
  <p><strong>Some Code for more clarity:</strong></p>
  <pre><code>import spiders.Linkedin as linkedinSpider
  
  linkedinSpider.main(numberOfPages=1, keywords=&quot;ios developer&quot;, location=&quot;US&quot;)
  </code></pre>
  <p>This piece of Code works fine and helps me to fetch and store data into database and returns <strong>True</strong> if saved successfully else <strong>False</strong>. I just need to call this function and all the work is done for me.</p>
  <p>Similarly,</p>
  <p>This is how i get data from the user through API from ADMIN Side using KTOR. Also this works fine.</p>
  <pre><code>            // Fetchs New Jobs.
              get(&quot;/fetch&quot;) {
                  val numberOfPages = call.request.queryParameters[&quot;pages&quot;]?.toInt() ?: 1
                  val keyword = call.request.queryParameters[&quot;keyword&quot;]
                  val location = call.request.queryParameters[&quot;location&quot;]
  
                  if (numberOfPages &lt; 1) {
                      call.respond(
                          status = HttpStatusCode.BadRequest,
                          message = Message(message = &quot;Incorrect Page Number.&quot;)
                      )
                  } else {
                      call.respond(
                          status = HttpStatusCode.PK,
                          message = Message(message = &quot;Process Completed.&quot;)
                      )
                  }
              }
  </code></pre>
  <p>This is how i wanted the code to work logically.</p>
  <pre><code>      // Fetch New Jobs.
              get(&quot;/fetch&quot;) {
                  val numberOfPages = call.request.queryParameters[&quot;pages&quot;]?.toInt() ?: 1
                  val keyword = call.request.queryParameters[&quot;keyword&quot;]
                  val location = call.request.queryParameters[&quot;location&quot;]
  
                  if (numberOfPages &lt; 1) {
                      call.respond(
                          status = HttpStatusCode.BadRequest,
                          message = Message(message = &quot;Incorrect Page Number.&quot;)
                      )
                  } else {
  
                      // TODO: Call Python Function Here and Check the Return Type. Something Like This.
                      if(linkedinSpider.main(numberOfPages=numberOfPages, keywords=keyword, location=location)) {
                          call.respond(
                              status = HttpStatusCode.OK,
                              message = Message(message = &quot;Process Completed.&quot;)
                          )
                      } else {
                          call.respond(
                              status = HttpStatusCode.InternalServerError,
                              message = Message(message = &quot;Something Went Wrong.&quot;)
                          )
                      }
                  }
              }
  </code></pre>
  <p>Also these are two different individual projects. Do i need to merge them or something as when i tried it says no python interpreter found in <strong>intelliJ</strong> which i'm using as an IDE for <strong>Ktor Development</strong>. Also I tried to configure python interpreter but it seems of no use as it is not able to reference the variables or the python files.</p>
  <p><strong>Edit 1</strong></p>
  <p><strong>This is what i tried</strong></p>
  <pre><code>    val processBuilder = ProcessBuilder(
          &quot;python3&quot;, &quot;main.py&quot;
      )
  
      val exitCode = processBuilder.start().waitFor()
  
      if (exitCode == 0) {
          println(&quot;Process Completed.&quot;)
      } else {
          println(&quot;Something Went Wrong.&quot;)
      }
  }
  </code></pre>
  <p>The exitCode i am getting is <strong>2</strong>. But when i run the below code it works with exitCode <strong>0</strong>.</p>
  <pre><code>ProcessBuilder(&quot;python3&quot;, &quot;--version&quot;)
  </code></pre>
  <p><strong>Edit 2</strong></p>
  <p><strong>After This the code is working but not terminating and i get no output</strong></p>
  <p>This is the kotlin file i made to simulate the problem</p>
  <pre><code>package com.bhardwaj.routes
  
  import java.io.File
  
  
  fun main() {
      val processBuilder = ProcessBuilder(
          &quot;python3&quot;, &quot;main.py&quot;, &quot;1&quot;, &quot;android&quot;, &quot;india&quot;
      )
      processBuilder.directory(File(&quot;src/main/kotlin/com/bhardwaj/&quot;))
      val process = processBuilder.start()
      val exitCode = process.waitFor()
  
      if (exitCode == 0) {
          val output = String(process.inputStream.readBytes())
          print(&quot;Process Completed -&gt; $output&quot;)
      } else {
          val output = String(process.errorStream.readBytes())
          print(&quot;Something went wrong -&gt; $output&quot;)
      }
  }
  </code></pre>
  <p>If i run same commands in terminal it works.</p>
  <pre><code>python3 src/main/kotlin/com/bhardwaj/main.py 1 &quot;android&quot; &quot;india&quot;
  
  </code></pre>
  <p><a href="https://i.stack.imgur.com/GK7hI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GK7hI.png" alt="enter image description here" /></a></p>
  <p>After i run same commands in the Terminal the output is -&gt;</p>
  <p><a href="https://i.stack.imgur.com/kfBml.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kfBml.png" alt="enter image description here" /></a></p>
  <p><strong>Edit 3</strong></p>
  <p>When I stopped default Scrapy logging, the code worked. It seems there is some limit to output stream in Process Builder. Here is what i did.</p>
  <pre><code>def __init__(self, number_of_pages=1, keywords=&quot;&quot;, location=&quot;&quot;, **kwargs):
          super().__init__(**kwargs)
          logging.getLogger('scrapy').setLevel(logging.WARNING)
  </code></pre>
  <p>This worked flawlessly in Development mode. But there is something more i want to discuss.
  When I deployed the same on Heroku and made a get request that gives me <strong>503 service unavailable</strong> after 30-40 sec later. But after another 20-30 sec i get my data into database. It's seems to be very confusing why this is happening.</p>
  <p><strong>For the flow of the program and clarity -</strong>
  When i make get request to <strong>ktor</strong>, it request scrapy(A python program) to scrape data and store it in <strong>JSON</strong> file. After all the process done it make a request to another endpoint to store all the data to database and after all this it returns and respond the user with the particular status code it should give as output using <code>call.respond</code> in <strong>ktor</strong>.</p>
  <p>Is the issue is due to another request made by the python program to the endpoint or it is related to heroku that we can handle one process at a time. Because there is no issue on <strong>development mode</strong> i.e. <code>localhost url</code></p>