2014-12-04 35 views
0

我無法重新啓動suprocess調用,從python中的函數內部工作。使用子進程調用從Python函數重新啓動linux服務器

下面的代碼

#!/usr/bin/python 
import subprocess 
def rebootscript(): 
    print "rebooting system" 
    command = "/sbin/reboot" 
    subprocess.call(command, shell = True) 

if __name__ == '__main__': 
    rebootscript 

如果我運行從主代碼(不是在一個功能)相同的代碼它的工作原理。我究竟做錯了什麼?

回答

0

嘗試調用實際的功能:

if __name__ == '__main__': 
    rebootscript() 

表達rebootscript將簡單地評價函數對象沒有調用它。如果你這樣做的解釋,你會看到類似這樣的:

<function rebootscript at 0xffe1b7d4> 

括號意味着你要調用的函數,而不是隻評估它,其差異可以在下面的談話中可以看出:

$ python 
Python 2.7.8 (default, Jul 28 2014, 01:34:03) 
[GCC 4.8.3] on cygwin 
Type "help", "copyright", "credits" or "license" for more information. 

>>> def rebootscript(): 
...  print "Hello" 
... 

>>> rebootscript 
<function rebootscript at 0xffe1bed4> 

>>> rebootscript() 
Hello 

>>> _ 
+0

謝謝!那簡單的括號就是問題所在。我很感激幫助 – damcoder 2014-12-04 22:48:21

0

您還沒有提到錯誤,但您可能有權限問題。如果您收到一個錯誤,如:

reboot: must be superuser. 
1 

的解釋,你需要執行呼叫作爲超級用戶。

當您使用python yourcode.py運行並且成功時,您的會話可能具有超級用戶權限。

乾杯。

相關問題