本文整理汇总了Python中subprocess.list2cmdline函数的典型用法代码示例。如果您正苦于以下问题:Python list2cmdline函数的具体用法?Python list2cmdline怎么用?Python list2cmdline使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了list2cmdline函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_disabled
def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
if has_powershell():
cmd = 'Get-WmiObject win32_service | where {$_.startmode -ne "Auto"} | select-object name'
lines = __salt__['cmd.run'](cmd, shell='POWERSHELL').splitlines()
return sorted([line.strip() for line in lines[3:]])
else:
ret = set()
services = []
cmd = list2cmdline(['sc', 'query', 'type=', 'service', 'state=', 'all', 'bufsize=', str(BUFFSIZE)])
lines = __salt__['cmd.run'](cmd).splitlines()
for line in lines:
if 'SERVICE_NAME:' in line:
comps = line.split(':', 1)
if not len(comps) > 1:
continue
services.append(comps[1].strip())
for service in services:
cmd2 = list2cmdline(['sc', 'qc', service])
lines = __salt__['cmd.run'](cmd2).splitlines()
for line in lines:
if 'DEMAND_START' in line:
ret.add(service)
elif 'DISABLED' in line:
ret.add(service)
return sorted(ret)
示例2: backup
def backup(self):
if self.dry_run:
return
if not os.path.exists(self.config['tar']['directory']) \
or not os.path.isdir(self.config['tar']['directory']):
raise BackupError('{0} is not a directory!'.format(self.config['tar']['directory']))
out_name = "{0}.tar".format(
self.config['tar']['directory'].lstrip('/').replace('/', '_'))
outfile = os.path.join(self.target_directory, out_name)
args = ['tar', 'c', self.config['tar']['directory']]
errlog = TemporaryFile()
stream = self._open_stream(outfile, 'w')
LOG.info("Executing: %s", list2cmdline(args))
pid = Popen(
args,
stdout=stream.fileno(),
stderr=errlog.fileno(),
close_fds=True)
status = pid.wait()
try:
errlog.flush()
errlog.seek(0)
for line in errlog:
LOG.error("%s[%d]: %s", list2cmdline(args), pid.pid, line.rstrip())
finally:
errlog.close()
if status != 0:
raise BackupError('tar failed (status={0})'.format(status))
示例3: run_tophat2_paired
def run_tophat2_paired(project_dir, sample, index_basename, fastq_r1, fastq_r2, logger):
'''Run tophat2 in paired-end mode for fastq files.
'''
logger.info('***Running tophat2 on paired-end reads; aligned to ref %s' % index_basename)
filepath = os.path.join(project_dir, sample)
args = [
'/Applications/tophat-2.1.0.OSX_x86_64/tophat2', #temp path for testing
#'/home/seqproc/tophat2/'
'--num-threads','10',
'--mate-inner-dist','200',
'--max-multihits' ,'1',
'--splice-mismatches', '1',
index_basename,
os.path.join(filepath, fastq_r1),
os.path.join(filepath, fastq_r2)
]
print subprocess.list2cmdline(args)
top2_process = subprocess.call(args)
if not top2_process: #return code of 0 is success
logger.info(
'***Bowtie2 alignment completed successfully for %s' % filepath
)
else:
logger.info(
'***Error in bowtie2 alignment. Return code: %d' % top2_process
)
示例4: run_task
def run_task(task_name, task, config):
if task is None:
return
target = task["target"]
positional_args = parse_list_arg(
task.get("args", {}).get("positional", []),
config,
config.get("mipmip.arg_policy." + task_name, {}).get("positional", {}),
False,
)
joined_named_args = parse_dict_arg(
task.get("args", {}).get("named", {}),
config,
config.get("mipmip.arg_policy." + task_name, {}).get("named", {}),
False,
)
stdout_pipe = None
for artifact_name, artifact in task.get("artifacts", {}).viewitems():
if artifact["type"] == "stdout":
stdout_pipe = subprocess.PIPE
args = [target] + positional_args + joined_named_args
print subprocess.list2cmdline(args)
p = subprocess.Popen(args, stdout=stdout_pipe)
returncode = p.wait()
if returncode == 0:
for artifact_name, artifact in task.get("artifacts", {}).viewitems():
if artifact["type"] == "stdout":
config["mipmip.artifacts." + task_name + "." + artifact_name] = p.stdout.read()
return p.returncode
示例5: run_pgdump
def run_pgdump(dbname, output_stream, connection_params, format='custom', env=None):
"""Run pg_dump for the given database and write to the specified output
stream.
:param db: database name
:type db: str
:param output_stream: a file-like object - must have a fileno attribute
that is a real, open file descriptor
"""
args = [ 'pg_dump' ] + connection_params + [
'--format', format,
dbname
]
LOG.info('%s > %s', subprocess.list2cmdline(args),
output_stream.name)
stderr = tempfile.TemporaryFile()
returncode = subprocess.call(args,
stdout=output_stream,
stderr=stderr,
env=env,
close_fds=True)
stderr.flush()
stderr.seek(0)
for line in stderr:
LOG.error('%s', line.rstrip())
stderr.close()
if returncode != 0:
raise OSError("%s failed." %
subprocess.list2cmdline(args))
示例6: Config_and_build_own
def Config_and_build_own(self):
'''
Build all the own libraries that are used for SaRoMaN
'''
#digi_ND
#run configure and autogen in that context.
command = self.exec_base+'/digi_ND/autogen.sh'
print command
subprocess.call('bash %s' %command, shell=True, cwd = self.exec_base+'/digi_ND')
subprocess.call('bash %s' %command, shell=True, cwd = self.exec_base+'/digi_ND')
command = self.exec_base+'/digi_ND/configure'
print command
subprocess.call('bash %s' %command, shell=True, cwd = self.exec_base+'/digi_ND')
subprocess.call('make', shell=True, cwd = self.exec_base+'/digi_ND')
#mind_rec
#run configure and autogen in that context.
command = self.exec_base+'/mind_rec/autogen.sh'
print command
subprocess.call('bash %s' %command, shell=True, cwd = self.exec_base+'/mind_rec')
subprocess.call('bash %s' %command, shell=True, cwd = self.exec_base+'/mind_rec')
command = self.exec_base+'/mind_rec/configure'
print command
subprocess.call('bash %s' %command, shell=True, cwd = self.exec_base+'/mind_rec')
subprocess.call('make', shell=True, cwd = self.exec_base+'/mind_rec')
#sciNDG4
command = [self.third_party_support+'/bin/scons']
print subprocess.list2cmdline(command)
subprocess.call(command, cwd = self.exec_base+'/sciNDG4', env=os.environ)
示例7: matlab_despike_command
def matlab_despike_command(func):
import os
import subprocess
# make sure your nifti is unzipped
cur_dir = os.getcwd()
matlab_command = ['matlab',
'-nodesktop' ,
'-nosplash',
'-r "WaveletDespike(\'%s\',\'%s/rest_dn\', \'wavelet\', \'d4\', \'LimitRAM\', 17) ; quit;"' %(func, cur_dir)]
print ''
print 'Running matlab through python...........Bitch Please....'
print ''
print subprocess.list2cmdline(matlab_command)
print ''
subprocess.call(matlab_command)
spike_percent = [os.path.join(cur_dir,i) for i in os.listdir(cur_dir) if 'SP' in i][0]
noise_img = [os.path.join(cur_dir,i) for i in os.listdir(cur_dir) if 'noise' in i][0]
despiked_img = [os.path.join(cur_dir,i) for i in os.listdir(cur_dir) if 'wds' in i][0]
return despiked_img, noise_img, spike_percent
示例8: main
def main():
if (len(sys.argv) != 2):
print "Usage: ./submit_problem.py problem_file"
exit(1)
if (str.find(sys.argv[1], '-') == -1):
print "Solution file format: id-infostring.txt"
exit(1)
solution_file = sys.argv[1]
if (str.find(solution_file, '/') != -1):
id_start_idx = len(solution_file) - 1 - str.index(solution_file[::-1], '/')
else:
id_start_idx = 0
id_end_idx = str.index(solution_file, '-')
problem_id = solution_file[id_start_idx+1:id_end_idx]
cmd_list = [
"curl",
"--compressed",
"-L",
"-H", "Expect:",
"-H", "X-API-Key: " + API_KEY,
"-F", "problem_id=" + problem_id,
"-F", "[email protected]" + solution_file,
SUBMIT_ENDPOINT
]
print subprocess.list2cmdline(cmd_list)
out_json = subprocess.check_output(cmd_list)
print out_json
示例9: run
def run(cls, cmd, *args, **argd):
extraflags = argd.get('extraflags', [])
if type(extraflags) not in (list, tuple):
extraflags = [extraflags]
cmd = [g_drive_bin] + [cmd] + list(extraflags) + list(args)
#print '$',
if argd.get('input') is not None:
if re.match(r'^[\x32-\x79\n]+$', argd.get('input')):
print 'echo "%s" |' % argd.get('input'),
else:
print 'echo ... |',
print subprocess.list2cmdline(cmd)
try:
cwd = os.getcwd()
os.chdir(g_testdir)
if argd.get('input') is None:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
finally:
os.chdir(cwd)
out, err = p.communicate(argd.get('input'))
return p.returncode, out, err
示例10: _exec_wrapper
def _exec_wrapper(self, type, args, root=None, arch=None,
outputlogger=None, timeout=None, ignoreerrors=False,
interactive=False, quiet=False, ignorestderr=False,
remount=False):
assert not (interactive and outputlogger)
basecmd = self.jurtrootcmd[:]
basecmd.extend(("--type", type))
basecmd.extend(("--target", self.targetname))
if timeout is not None:
basecmd.extend(("--timeout", str(timeout)))
if root is not None:
basecmd.extend(("--root", root))
if remount:
basecmd.append("--remount")
if arch is not None:
basecmd.extend(("--arch", arch))
if ignoreerrors:
basecmd.append("--ignore-errors")
if quiet:
basecmd.append("--quiet")
if ignorestderr:
basecmd.append("--ignore-stderr")
basecmd.extend(args)
if interactive:
fullcmd = self.sucmd[:]
fullcmd.extend(basecmd)
cmdline = subprocess.list2cmdline(fullcmd)
proc = subprocess.Popen(args=fullcmd, shell=False, bufsize=-1)
proc.wait()
returncode = proc.returncode
output = "(interactive command, no output)"
else:
cmdline = subprocess.list2cmdline(basecmd)
if outputlogger and not quiet:
outputlogger.write(">>>> running privilleged agent: %s\n" % (cmdline))
outputlogger.flush()
if not self.agentrunning:
self.start()
logger.debug("sending command to agent: %s", cmdline)
self.agentproc.stdin.write(cmdline + "\n")
self.agentproc.stdin.flush()
if outputlogger:
targetfile = outputlogger
else:
targetfile = StringIO()
returncode = self._collect_from_agent(targetfile, outputlogger)
if outputlogger:
output = "(error in log available in log files)"
else:
output = targetfile.getvalue()
# check for error:
if returncode != 0:
if timeout is not None and returncode == 124:
# command timeout
raise CommandTimeout, ("command timed out:\n%s\n" %
(cmdline))
raise CommandError(returncode, cmdline, output)
return output
示例11: main
def main(sys_args):
sys_args, jython_opts = decode_args(sys_args)
args, jython_args = parse_launcher_args(sys_args)
jython_command = JythonCommand(args, jython_opts + jython_args)
command = jython_command.command
if args.profile and not args.help:
try:
os.unlink("profile.txt")
except OSError:
pass
if args.print_requested and not args.help:
if jython_command.uname == "windows":
print subprocess.list2cmdline(jython_command.command)
else:
print " ".join(pipes.quote(arg) for arg in jython_command.command)
else:
if not (is_windows or not hasattr(os, "execvp") or args.help or jython_command.uname == "cygwin"):
# Replace this process with the java process.
#
# NB such replacements actually do not work under Windows,
# but if tried, they also fail very badly by hanging.
# So don't even try!
os.execvp(command[0], command[1:])
else:
result = 1
try:
result = subprocess.call(command)
if args.help:
print_help()
except KeyboardInterrupt:
pass
sys.exit(result)
示例12: _exec_command_line
def _exec_command_line( command, prefix ):
"""
Executes a command (from a string), allowing all output to pass to STDOUT.
"""
# split the arguments
arguments = shlex.split( command )
# attempt to detect generic commands (not a relative command)
proc = arguments[ 0 ]
# this is probably a generic/system command
if proc[ 0 ] != '.':
check = _which( proc )
if check is None:
raise RuntimeError(
'Unable to locate "{}" in path.'.format( proc )
)
arguments[ 0 ] = check
# this needs to be executed relative to the prefix
else:
arguments[ 0 ] = prefix + arguments[ 1 : ]
# print the statement we're about to execute
print subprocess.list2cmdline( arguments )
# attempt to execute the requested command
result = subprocess.call( arguments )
# return the result of the command
return result
示例13: lvsnapshot
def lvsnapshot(orig_lv_path, snapshot_name, snapshot_extents, chunksize=None):
"""Create a snapshot of an existing logical volume
:param snapshot_lv_name: name of the snapshot
:param orig_lv_path: path to the logical volume being snapshotted
:param snapshot_extents: size to allocate to snapshot volume in extents
:param chunksize: (optional) chunksize of the snapshot volume
"""
lvcreate_args = [
"lvcreate",
"--snapshot",
"--name",
snapshot_name,
"--extents",
"%d" % snapshot_extents,
orig_lv_path,
]
if chunksize:
lvcreate_args.insert(-1, "--chunksize")
lvcreate_args.insert(-1, chunksize)
LOG.debug("%s", list2cmdline(lvcreate_args))
process = Popen(lvcreate_args, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid, close_fds=True)
stdout, stderr = process.communicate()
for line in stdout.splitlines():
if not line:
continue
LOG.debug("lvcreate: %s", line)
if process.returncode != 0:
raise LVMCommandError(list2cmdline(lvcreate_args), process.returncode, str(stderr).strip())
示例14: cmd
def cmd( cmd, args = [], raw = False, show = False ):
""" executes a command returning the output as a string """
# prepend the base command
args.insert( 0, cmd )
# check for a raw command (no interpreted arguments)
if raw == True:
cmd_args = ' '.join( args )
if show == True:
print cmd_args
# normal command (list of arguments)
else:
cmd_args = args
if show == True:
print subprocess.list2cmdline( cmd_args )
# call the command expecting to see string output
output = subprocess.check_output( cmd_args,
stderr = subprocess.STDOUT,
shell = True,
universal_newlines = True )
# return the output of the command
return output.strip()
示例15: enable
def enable(self):
proxies = ('%s=%s' % (_, self.__get_proxy(_))
for _ in self.__env_names)
print(list2cmdline(['export'] + list(proxies)))
aliases = ('%s=%s' % (_, self.__get_proxy('GIT_SSH'))
for _ in self.__ssh_aliases)
print(list2cmdline(['alias'] + list(aliases)))