python: 3.6.5
airetest ios需要执行两部shell命令,且需要一直执行,借用python来后台执行
之前的功能是网上转载的,由于业务需求,读了下subprocess源码,新增了个kill功能,实现终止后台运行的shell
#coding:utf-8
import subprocess, time
class Shell(object):
def __init__(self, cmd):
self.cmd = cmd
self.ret_code = None
self.ret_info = None
self.err_info = None
def run_background(self):
self._process = subprocess.Popen(self.cmd, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def get_status(self):
retcode = self._process.poll()
if retcode == None:
status = "RUNNING"
else:
status = "FINISHED"
return status
def print_output(self):
for _ in range(6):
line = self._process.stdout.readline() # 这儿会阻塞
if line:
print ("output:",line)
else: # 只有子进程结束后, 才会有readline返回""的情况
print ("no ouput yet")
def kill(self):
self._process.kill()
shells = '/usr/bin/xcodebuild -project WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner -destination id=`system_profiler SPUSBDataType | grep "Serial Number:.*" | sed s#".*Serial Number: "##` test'
keepprinting1 = Shell(shells)
keepprinting1.run_background()
keepprinting1.print_output()
keepprinting2 = Shell("iproxy 8100 8100") # keepprint will print out one line every 2 seconds
keepprinting2.run_background()
keepprinting2.print_output()
count = 0
while True:
print("====running===="+str(count))
count+=1
print(keepprinting1.get_status())
print(keepprinting2.get_status())
time.sleep(2)
if count == 7:
keepprinting1.kill()#终止后台线程1
osx: 10.15python: 3.6.5airetest ios需要执行两部shell命令,且需要一直执行,借用python来后台执行#coding:utf-8import subprocess, timeclass Shell(object): def __init__(self, cmd): self.cmd = cmd se...
一些时间长的命令经常需要在
后台运行
,但苦于通常我们都是通过PC去连接服务器,一直保持ssh连接是不太现实的,这时就需要一些命令使得断开ssh连接后服务器依旧在运行命令。
命令后面加&在
后台运行
python
test.py > test.log 2>&1 &
>表示将标准输出(STDOUT)重定向到test.log文件;2&...
深度学习在x
shell
上训练网络模型往往会花费非常久的时间,而在
shell
上提交训练任务后,关闭电脑的话,程序也会随之中断结束,非常受约束。那么怎么才能够让程序在
后台运行
,电脑随便关机重启呢?
在
shell
中使用以下命令即可:
nohup
python
train.py >log_1.log 2>&1 &
运行后会得到一个程序号,例如 “23766” 这种。这样程序就在
后台
跑起来了,退出程序不能直接关掉
shell
,要输入 exit 退出账户。本来输出的结果会存储在./log_1
1、os模块中的os.system()这个函数来
执行
shell
命令
>>> os.system('ls')
anaconda-ks.cfg install.log install.log.syslog send_sms_service.py sms.py
0注,这个方法得不到
shell
命令的输出。
今天为大家带来的内容,主要介绍了
Python
脚本
后台运行
的几种方式,linux下
后台运行
、通过upstart方式实现、通过bash脚本实现、通过screen、tmux等方式实现,需要的朋友可以参考下。
提示:部分代码用图片方式呈现出来,目的是为了更好的收藏与观看!喜欢的话记得不忘点赞关注不迷路哦!
一个用
python
写的监控脚本test1.py,用while True方式一直运行,在...
上面的代码中,我们使用`subprocess.run`方法
执行
`ls -l`命令,并将结果保存在`result`变量中。然后,我们使用`result.stdout.decode('utf-8')`方法将结果转换为字符串,并输出结果。
在`subprocess.run`方法中,第一个参数是一个包含命令及其参数的列表,第二个参数是标准输出流的处理方式。`subprocess.PIPE`表示将结果保存在管道中,可用于后续处理。