本文整理汇总了Python中psutil.Popen.wait方法的典型用法代码示例。如果您正苦于以下问题:Python Popen.wait方法的具体用法?Python Popen.wait怎么用?Python Popen.wait使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类psutil.Popen
的用法示例。
在下文中一共展示了Popen.wait方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: system
# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import wait [as 别名]
def system(cmd, timeout = 60):
global proc
logger().info(u"Executing command '{0}'".format(cmd))
proc = Popen(cmd, close_fds=True, shell=True, stdout=PIPE)
logger().info(u"PID is {0} for command '{1}'".format(proc.pid, cmd))
for line in proc.stdout:
logger().info(u"Process output: {0}".format(line.decode('latin1')))
## Kill process after timeout seconds.
_timer = Timer(timeout, terminate_process, [proc])
_timer.start()
proc.wait(timeout=3) ## Wait for process to complete, increase timeout parameter if default 3 seconds is not enough
_timer.cancel()
return proc
示例2: make
# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import wait [as 别名]
def make(base_dir, timeout=5):
"""compile source code.
return (ok?, msg)"""
cmd = ['clang++', '-std=c++11', 'main.cpp']
p = Popen(cmd, stderr=PIPE, cwd=base_dir)
try:
p.wait(timeout)
except TimeoutExpired:
return False, 'compilation take too much time.'
else:
if p.returncode == 0:
return True, ''
else:
return False, p.communicate()[1]
示例3: run
# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import wait [as 别名]
def run(base_dir, timeout):
"""run the program.
return (ok?, msg)"""
cmd = ['./a.out']
out_path = os.path.join(base_dir, 'test.out')
in_path = os.path.join(base_dir, 'test.in')
with open(out_path, 'w') as fout, open(in_path) as fin:
p = Popen(cmd, stdin=fin, stdout=fout, cwd=base_dir)
try:
p.wait(timeout)
except TimeoutExpired:
p.kill()
return False, 'time limit exceed'
else:
if p.returncode == 0:
return True, ''
else:
return False, 'runtime error'
示例4: test_streams
# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import wait [as 别名]
def test_streams(self):
self.sniff_log()
print('test1')
with log_std_streams(logger=self.captured_logger, stdout_level=logging.DEBUG):
print('test2')
with log_std_streams(stdout_level=logging.DEBUG):
print('test3')
with log_std_streams(stdout_level=logging.DEBUG):
sys.stdout.write('test3')
with log_std_streams(logger=self.captured_logger, stdout_level=logging.DEBUG):
cmd = ['echo', '"test5"']
if is_windows():
cmd = ['cmd', '/c'] + cmd
process = Popen(cmd)
process.wait()
missed_file = get_uniq_name('.', 'test6', '')
with log_std_streams(logger=self.captured_logger, stderr_level=logging.WARNING):
if is_windows():
cmd = ['cmd', '/c', 'dir']
else:
cmd = ['ls']
process = Popen(cmd + [missed_file])
process.wait()
debug_buf = self.log_recorder.debug_buff.getvalue()
warn_buf = self.log_recorder.warn_buff.getvalue()
self.assertNotIn('test1', debug_buf)
self.assertIn('test2', debug_buf)
self.assertNotIn('test3', debug_buf)
self.assertIn('test5', debug_buf)
self.assertTrue(len(warn_buf) > 0)
示例5: find_device
# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import wait [as 别名]
def find_device(self):
for drive in disk_partitions(False):
if 'removable' in drive[3]:
if os.path.isdir(os.path.join(drive[1], 'system')) and \
os.path.isdir(os.path.join(drive[1], 'documents')):
return drive[1]
# print(self.config['GENERAL']['SSHEnabled'])
if self.config['GENERAL']['SSHEnabled'] == "True":
ssh = Popen('"' + self.config['SSH']['PLinkPath'] + '" [email protected]' + self.config['SSH']['KindleIP']
+ ' whoami', stdout=PIPE, stderr=STDOUT, shell=True)
ssh_check = ssh.wait()
if ssh_check == 0:
self.ssh = True
return self.config['SSH']['KindleIP']
else:
raise OSError('Can\'t connect to Kindle!')
else:
raise OSError('Not found any connected Kindle!')
示例6: save_file
# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import wait [as 别名]
def save_file(self, cover,directory,getcover,cloud, cover_size):
if(self.mode=='reader'):
# need.cover means that directory system/thumbnails has been found on the Kindle (this is Kindle PW)
if self.kindle.need_cover:
if cover != '':
try:
ready_cover = Image.open(cover)
# ready_cover.thumbnail((217, 330), Image.ANTIALIAS)
if self.cover_size =='pw':
ready_cover = ready_cover.resize((217, 330), Image.ANTIALIAS)
else:
ready_cover = ready_cover.resize((330, 470), Image.ANTIALIAS)
ready_cover = ready_cover.convert('L')
self.txt2img(self.title, self.seqnumber, ready_cover, self.position)
except:
raise OSError('Failed to load custom cover!')
else:
if getcover=='search': # search for cover
try:
ready_cover = self.get_cover_image()
except:
if(self.write_thumb):
#raise OSError('Failed to extract cover!')
try:
if sys.frozen or sys.importers:
butler_dir = os.path.dirname(sys.executable)
except AttributeError:
butler_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
path_to_cover = butler_dir + "\\default_banner.jpeg"
ready_cover = Image.open(path_to_cover)
if self.cover_size =='pw':
ready_cover = ready_cover.resize((217, 330), Image.ANTIALIAS)
else:
ready_cover = ready_cover.resize((330, 470), Image.ANTIALIAS)
ready_cover = ready_cover.convert('L')
self.txt2defaultcover(self.title, self.author, self.seqnumber, ready_cover, self.position )
else: # extract cover
try:
# ready_cover = self.get_cover_image()
extractcover_34.extractThumbnail(self.path, "tmpdir.$$$");
shutil.rmtree("tmpdir.$$$")
coverfile = 'images.$$$' + '\\' + self.infilename +'.cover' + '.jpeg'
ready_cover = Image.open(coverfile)
ready_cover = ready_cover.resize((217, 330), Image.ANTIALIAS)
ready_cover = ready_cover.convert('L')
self.txt2img(self.title, self.seqnumber, ready_cover, self.position)
shutil.rmtree("images.$$$")
except:
if(self.write_thumb):
#shutil.rmtree("images.$$$")
#raise OSError('Failed to extract cover!')
try:
if sys.frozen or sys.importers:
butler_dir = os.path.dirname(sys.executable)
except AttributeError:
butler_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
path_to_cover = butler_dir + "\\default_banner.jpeg"
ready_cover = Image.open(path_to_cover)
if self.cover_size =='pw':
ready_cover = ready_cover.resize((217, 330), Image.ANTIALIAS)
else:
ready_cover = ready_cover.resize((330, 470), Image.ANTIALIAS)
ready_cover = ready_cover.convert('L')
self.txt2defaultcover(self.title, self.author, self.seqnumber, ready_cover, self.position)
if self.kindle.ssh:
tmp_cover = os.path.join(gettempdir(), 'KindleButlerCover')
ready_cover.save(tmp_cover, 'JPEG')
ssh = Popen('"' + self.config['SSH']['PSCPPath'] + '" "' + tmp_cover + '" [email protected]' + self.kindle.path +
':/mnt/us/system/thumbnails/thumbnail_' + self.asin + '_EBOK_portrait.jpg',
stdout=PIPE, stderr=STDOUT, shell=True)
ssh_check = ssh.wait()
if ssh_check != 0:
raise OSError('Failed to upload cover!')
os.remove(tmp_cover)
else:
if(self.write_thumb):
if(cloud=='no'):
ready_cover.save(os.path.join(self.kindle.path, 'system',
'thumbnails', 'thumbnail_' + self.asin + '_EBOK_portrait.jpg'), 'JPEG')
else:
# get ASIN from file
section = KindleUnpack.Sectionizer(self.path)
mhlst = [KindleUnpack.MobiHeader(section, 0)]
mh = mhlst[0]
metadata = mh.getmetadata()
assa = metadata.get('ASIN')
assassin = assa[0].decode("utf-8")
if assassin==None:
assassin='None'
ready_cover.save(os.path.join(self.kindle.path, 'system',
'thumbnails', 'thumbnail_' + assassin + '_PDOC_portrait.jpg'), 'JPEG')
# for all modes prepare processed file
try:
# noinspection PyArgumentList
ready_file = DualMetaFix.DualMobiMetaFix(self.path, bytes(self.asin,'UTF-8'),cloud)
except:
raise OSError('E-Book modification failed!')
ready_file, source_size = ready_file.getresult()
#.........这里部分代码省略.........
示例7: check_cmd_output
# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import wait [as 别名]
def check_cmd_output(cmd):
proc = Popen(cmd, stdout=PIPE, shell=True)
exit_code = proc.wait(timeout=5)
if exit_code != 0:
raise ValueError(u"No HDHR device found")
return proc.stdout
示例8: Process
# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import wait [as 别名]
#.........这里部分代码省略.........
@debuglog
def stop(self):
"""Stop the process and close stdout/stderr
If the corresponding process is still here
(normally it's already killed by the watcher),
a SIGTERM is sent, then a SIGKILL after 1 second.
The shutdown process (SIGTERM then SIGKILL) is
normally taken by the watcher. So if the process
is still there here, it's a kind of bad behavior
because the graceful timeout won't be respected here.
"""
try:
try:
if self.is_alive():
try:
return self._worker.terminate()
except AccessDenied:
# It can happen on Windows if the process
# dies after poll returns (unlikely)
pass
finally:
self.close_output_channels()
except NoSuchProcess:
pass
def close_output_channels(self):
if self._worker.stderr is not None:
self._worker.stderr.close()
if self._worker.stdout is not None:
self._worker.stdout.close()
def wait(self, timeout=None):
"""
Wait for the process to terminate, in the fashion
of waitpid.
Accepts a timeout in seconds.
"""
self._worker.wait(timeout)
def age(self):
"""Return the age of the process in seconds."""
return time.time() - self.started
def info(self):
"""Return process info.
The info returned is a mapping with these keys:
- **mem_info1**: Resident Set Size Memory in bytes (RSS)
- **mem_info2**: Virtual Memory Size in bytes (VMS).
- **cpu**: % of cpu usage.
- **mem**: % of memory usage.
- **ctime**: process CPU (user + system) time in seconds.
- **pid**: process id.
- **username**: user name that owns the process.
- **nice**: process niceness (between -20 and 20)
- **cmdline**: the command line the process was run with.
"""
try:
info = get_info(self._worker)
except NoSuchProcess:
return "No such process (stopped?)"
示例9: Run
# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import wait [as 别名]
#.........这里部分代码省略.........
txt_mode = False
popen_args = {
'stdin': stdin,
'stdout': stdout,
'stderr': self.error_file.fd,
'cwd': cwd,
'env': env,
'universal_newlines': txt_mode}
if sys.platform != 'win32' and set_sigpipe:
# preexec_fn is no supported on windows
popen_args['preexec_fn'] = subprocess_setup
try:
runs.append(Popen(cmd, **popen_args))
except OSError as e:
logger.error('error when spawning %s', cmd)
# We have an error (e.g. file not found), try to kill
# all processes already started.
for p in runs:
p.terminate()
raise
self.internal = runs[-1]
except Exception as e:
self.__error(e, self.cmds)
raise
self.pid = self.internal.pid
if not bg:
self.wait()
def command_line_image(self):
"""Get shell command line image of the spawned command(s).
:rtype: str
This just a convenient wrapper around the function of the same
name.
"""
return command_line_image(self.cmds)
def close_files(self):
"""Close all file descriptors."""
self.output_file.close()
self.error_file.close()
self.input_file.close()
def __error(self, error, cmds):
"""Set pid to -1 and status to 127 before closing files."""
self.close_files()
logger.error(error)
def not_found(path):
"""Raise OSError.
:param path: path of the executable
:type path: str
"""
logger.error("%s not found", path)
e3.log.debug('PATH=%s', os.environ['PATH'])
raise OSError(errno.ENOENT,
'No such file or directory, %s not found' % path)