簡體   English   中英

在從 crontab 調用的 python 腳本中執行 bash 命令

[英]Executing bash command within a python script called from crontab

我正在編寫一個 python 腳本,我想從 crontab 調用。 它腳本調用xrandr命令並將其輸出保存在一個變量中,如下所示: output = subprocess.run('xrandr', shell=True, stdout=subprocess.PIPE).stdout.decode('utf-8')我想要要保存在字符串中的xrandr輸出。 如果我從終端執行它,這一切正常,但如果我使用 cron 運行它,變量output保持為空。 其余代碼正常執行,所以 cron 不是問題。 那么我怎樣才能讓這個命令正確執行呢? 謝謝你的建議。

你想存儲輸出,你可以在這里使用communicate()來幫忙,就像這樣:

from subprocess import PIPE
output = subprocess.run('xrandr', shell=True, stdout=subprocess.PIPE).stdout.decode('utf-8')
text = output.communicate()[0]
print(text)

或者也許是這樣,在這種情況下,您可以不太確定地刪除.stdout.decode('utf-8')但它可以使用和不使用它:

from subprocess import PIPE
output = subprocess.run('xrandr', shell=True, stdout=subprocess.PIPE).stdout.decode('utf-8')
print(output.stdout)

我猜在 cron 環境中未設置 PATH 變量,因此您應該提供 xrandr 的絕對路徑(您可以通過which xrandr找到它)。 例如,如果這個路徑/usr/bin/xrandr試試

from subprocess import PIPE
output = subprocess.run('/usr/bin/xrandr', shell=True, stdout=subprocess.PIPE).stdout.decode('utf-8')
text = output.communicate()[0]
print(text)

我認為更好的方法是捕獲 stderr 並在發生錯誤時記錄錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM