我制作了一个脚本,它在本地执行并做一些远程工作例如:ssh python3 myscript
脚本本身几乎没有什么函数可以打印它们所做的一切例如,在一种状态下,我使用它来启用一些服务,即systemctl enable。。。然后打印是否启用
我遇到的问题:
当我像ssh <ip> python3 myscript
那样运行它时
输出应为:
Executing: /lib/systemd/systemd-sysv-install enable nginx
Nginx was enabled (Thats my print)
3 Nov 18:45:00 ntpdate[2312]: adjust time server 132.163.96.2 offset -0.00231 sec
ntp time synced by: 0.europe.pool.ntp.org (also my print from sync_ntp func)
但是实际输出是:
Executing: /lib/systemd/systemd-sysv-install enable nginx
*no print*
3 Nov 18:45:00 ntpdate[2312]: adjust time server 132.163.96.2 offset -0.00231 sec
*no print*
when script finish i got the prints:
Nginx was enabled
ntp time synced by: 0.europe.pool.ntp.org
def enable_nginx():
nginx = subprocess.Popen(['bash', 'systemctl', 'enable', 'nginx'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if nginx.wait() == 0: # i.e. OK
print("Nginx enabled")
else:
print("Nginx failed")
def sync_ntp():
ntpdate = subprocess.Popen(['ntpdate', '0.europe.pool.ntp.org'])
if ntpdate.wait() == 0:
print("Time synced by: 0.europe.pool.ntp.org")
else:
print("Cannot sync time")
以上是我的小功能片段
所以我不明白为什么打印排在最后,而它应该在启用nginx后立即打印,但它却在底部打印所有内容。。
在函数中,使用return
命令,而不是print
命令。