[英]Reading string from terminal using python
我想從終端讀取CPU的數量。
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)))
從os.system grep的線程數未傳遞到線程數中。 它采用空值。
參考https://docs.python.org/3/library/os.html#os.system
...返回值是流程的退出狀態...
該文檔繼續:
子流程模塊提供了更強大的功能來生成新流程並檢索其結果。 使用該模塊優於使用此功能。
基本上,os.system不允許您捕獲正在運行的子進程的輸出。 您應該看看subprocess.run
( https://docs.python.org/3/library/subprocess.html#subprocess.run )
抱歉,您以前誤解了這個問題,但是使用os.popen
應該可以捕獲進程數,並且正如我的評論所述, nproc
還可以幫助減少代碼:
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))
有關此信息的更多信息,此帖子非常有用
os.system()
函數返回shell的退出代碼,而不是執行該工作的shell命令的輸出。 要捕獲此輸出,您需要打開管道並從中讀取數據。 在os
模塊中執行此操作的方法是使用os.popen()
而不是os.system()
os.popen("""lscpu | grep 'CPU(s):' | head -1 | awk '{print $2}'""").read()
另一種方法是改用較新的subprocess
模塊。 由於os.popen()
從2.6版開始就已貶值 ,因此您可能更喜歡subprocess
,特別是如果您希望代碼在接下來的兩個Python版本中都能幸免。
subprocess.getoutput(""""lscpu | grep 'CPU(s):' | head -1 | awk '{print $2}'""")
旁注:我的三重引號在這里可能不是嚴格必要的,但我想將它們放在此類調用中,只是為了確保它們不會干擾任何shell命令中的任何引號。
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.