How to set the max thread a python script could use when calling from shell
<p>Have script a.py, it will run some task with multiple-thread, please noticed that I have no control over the a.py.</p>

<p>I'm looking for a way to limit the number of thread it could use, as I found that using more threads than my CPU core will slow down the script.</p>

<p>It could be something like:</p>

<p>python  --nthread=2 a.py </p>

<p>or Modifying something in my OS is also acceptable . </p>

<p>I am using ubuntu 16.04</p>

<p>As requested: </p>

<p>the a.py is just a module in scikit-learn the <a href="https://github.com/scikit-learn/scikit-learn/blob/183722475189b8e21ee2e621b19acca3c9e054d8/sklearn/neural_network/multilayer_perceptron.py" rel="nofollow">MLPRegressor</a> .
I also asked this question <a href="https://github.com/scikit-learn/scikit-learn/issues/7280" rel="nofollow">here</a>.</p>

<p>Read the <a href="https://docs.python.org/2/library/threading.html" rel="nofollow">threading</a> doc, it said:</p>

<blockquote>
  <p>CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.</p>
</blockquote>

<p>If you will like to take advantage of the multi-core processing better update the code to use <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">multiprocessing</a> module.</p>

<p>In case that you prefer anyway continue using threading, you have one option passing the number of threads to the application as an argument like:</p>

<pre><code>python a.py --nthread=2
</code></pre>

<p>Then you can update the script code to limit the threads.</p>

python multithreading scikit-learn