2

I want to read the number of CPU from the terminal.

Number_of_process_to_run = int(input("Number of Process you want to run : "))
number_of_threads = (os.system("lscpu | grep 'CPU(s):' | head -1 | awk '{print $2}'"))

nt = int (input("Your Number of Threads is :" +str(number_of_threads)))

The number of threads which is grepped from os.system is not passing into the number of threads. It's taking a null value.

Ron Ledger
  • 35
  • 7
  • 1
    Also, in addition to @Tom Dalton's answer, you can simplify your life a little by using `os.system("nproc")` instead... https://askubuntu.com/questions/724228/how-to-find-the-number-of-cpu-cores-including-virtual for reference – Dakota Maker Jun 24 '19 at 16:09
  • It won't solve my problem, I am unable to store the value of os.system. – Ron Ledger Jun 24 '19 at 16:18

3 Answers3

2

Ref https://docs.python.org/3/library/os.html#os.system

... the return value is the exit status of the process ...

The docs go on:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function.

Basically os.system doesn't allow you to capture the output of the subprocess you are running. You should have a look at subprocess.run (https://docs.python.org/3/library/subprocess.html#subprocess.run)

Tom Dalton
  • 6,122
  • 24
  • 35
1

Sorry for misinterpreting the question before, but using os.popen should capture the number of processes, and as my comment mentioned, nproc also helps reduce the code:

Number_of_process_to_run = int(input("Number of Process you want to run : "))
number_of_threads = int((os.popen("nproc").read()))

print('Your Number of Threads is: ' + str(number_of_threads))

For more info about it this SO post is very useful

Dakota Maker
  • 633
  • 4
  • 24
1

The os.system() function returns the exit code of the shell, not the output from the shell command that did the work. To capture this output, you need to open a pipe and read from it. The way to do this within the os module is to use os.popen() instead of os.system()

os.popen("""lscpu | grep 'CPU(s):' | head -1 | awk '{print $2}'""").read()

Another way is to use the newer subprocess module instead. Since os.popen() has been depreciated since version 2.6, you might prefer subprocess, especially if you expect your code to survive the next couple of Python revisions.

 subprocess.getoutput(""""lscpu | grep 'CPU(s):' | head -1 | awk '{print $2}'""")

Side note: My triple quotes may not be strictly necessary here, but I like to put them into such calls, just to make sure they don't interfere with any quotes inside of any shell commands.

Good luck!