本文整理汇总了Python中subprocess.getoutput函数的典型用法代码示例。如果您正苦于以下问题:Python getoutput函数的具体用法?Python getoutput怎么用?Python getoutput使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getoutput函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_antechamber
def run_antechamber(molecule_name, input_filename, charge_method="bcc", net_charge=None, gaff_mol2_filename=None, frcmod_filename=None):
"""Run AmberTools antechamber and parmchk2 to create GAFF mol2 and frcmod files.
Parameters
----------
molecule_name : str
Name of the molecule to be parameterized, will be used in output filenames.
ligand_filename : str
The molecule to be parameterized. Must be tripos mol2 format.
charge_method : str, optional
If not None, the charge method string will be passed to Antechamber.
net_charge : int, optional
If not None, net charge of the molecule to be parameterized.
If None, Antechamber sums up partial charges from the input file.
gaff_mol2_filename : str, optional, default=None
Name of GAFF mol2 filename to output. If None, uses local directory
and molecule_name
frcmod_filename : str, optional, default=None
Name of GAFF frcmod filename to output. If None, uses local directory
and molecule_name
Returns
-------
gaff_mol2_filename : str
GAFF format mol2 filename produced by antechamber
frcmod_filename : str
Amber frcmod file produced by prmchk
"""
ext = parse_ligand_filename(input_filename)[1]
filetype = ext[1:]
if filetype != "mol2":
raise(ValueError("Must input mol2 filename"))
if gaff_mol2_filename is None:
gaff_mol2_filename = molecule_name + '.gaff.mol2'
if frcmod_filename is None:
frcmod_filename = molecule_name + '.frcmod'
cmd = "antechamber -i %s -fi mol2 -o %s -fo mol2 -s 2" % (input_filename, gaff_mol2_filename)
if charge_method is not None:
cmd += ' -c %s' % charge_method
if net_charge is not None:
cmd += ' -nc %d' % net_charge
logger.debug(cmd)
output = getoutput(cmd)
logger.debug(output)
cmd = "parmchk2 -i %s -f mol2 -o %s" % (gaff_mol2_filename, frcmod_filename)
logger.debug(cmd)
output = getoutput(cmd)
logger.debug(output)
return gaff_mol2_filename, frcmod_filename
示例2: cpu_check
def cpu_check():
"""
TODO: split processor num / ssse3
"""
ret = {
"key": "cpu",
"cn_desc": "cpu",
}
output = getoutput('cat /proc/cpuinfo').splitlines()
# 某行类似processor : 3
lines = [l for l in output if l.strip() and l.split()[0] == 'processor']
cpu_num = len(lines)
fail_standalone = False
fail_cluster = False
fail_reason = ""
if cpu_num < CLUSTER_SYS_REQ['MIN_CPU_CORE_NUM']:
fail_cluster |= True
fail_reason = "集群版最低CPU核数:%d" % CLUSTER_SYS_REQ['MIN_CPU_CORE_NUM']
if cpu_num < STANDALONE_SYS_REQ['MIN_CPU_CORE_NUM']:
fail_standalone = True
fail_reason = fail_reason + ", 单机版最低CPU核数:%d" % STANDALONE_SYS_REQ['MIN_CPU_CORE_NUM']
support_ssse3 = len([l for l in output if 'flags' in l and 'ssse3' in l]) > 0
fail_cluster |= not support_ssse3
if not support_ssse3:
fail_reason = fail_reason + ", 集群版要求CPU支持ssse3指令集"
ret.update({
"value": "processor num: %d, support ssse3: %r" % (cpu_num, support_ssse3),
"pass_standalone": not fail_standalone,
"pass_cluster": not fail_cluster,
"fail_reason": fail_reason,
"lscpu": getoutput("lscpu"),
"proc_cpuinfo": getoutput("cat /proc/cpuinfo"),
})
return ret
示例3: create_db_image
def create_db_image(drucker):
"""Create database image from database container"""
print(
colorful.white_on_blue(
"Committing %s image from %s container..."
% (drucker.vars.DB_IMAGE, drucker.vars.DB_CONTAINER)
)
)
subprocess.run(
'docker commit -m "%s on %s" %s %s'
% (
drucker.vars.DB_CONTAINER,
str(date.today()),
drucker.vars.DB_CONTAINER,
drucker.vars.DB_IMAGE,
),
shell=True,
)
print(colorful.white_on_blue("Deleting initial container..."))
subprocess.getoutput(
"docker rm -f %s > /dev/null 2>&1" % (drucker.vars.DB_CONTAINER)
)
create_db_container(drucker)
示例4: run_pbs_jobs
def run_pbs_jobs(c, config_file, strategies_file, subject_list_file, p_name):
import subprocess
from time import strftime
try:
sublist = yaml.load(open(os.path.realpath(subject_list_file), 'r'))
except:
raise Exception ("Subject list is not in proper YAML format. Please check your file")
temp_files_dir = os.path.join(os.getcwd(), 'cluster_temp_files')
shell = subprocess.getoutput('echo $SHELL')
subject_bash_file = os.path.join(temp_files_dir, 'submit_%s.pbs' % str(strftime("%Y_%m_%d_%H_%M_%S")))
f = open(subject_bash_file, 'w')
print('#! %s' % shell, file=f)
print('#PBS -S %s' % shell, file=f)
print('#PBS -V', file=f)
print('#PBS -t 1-%d' % len(sublist), file=f)
print('#PBS -q %s' % c.queue, file=f)
print('#PBS -l nodes=1:ppn=%d' % c.numCoresPerSubject, file=f)
print('#PBS -e %s' % os.path.join(temp_files_dir, 'c-pac_%s.err' % str(strftime("%Y_%m_%d_%H_%M_%S"))), file=f)
print('#PBS -o %s' % os.path.join(temp_files_dir, 'c-pac_%s.out' % str(strftime("%Y_%m_%d_%H_%M_%S"))), file=f)
print('source ~/.bashrc', file=f)
print("python -c \"import CPAC; CPAC.pipeline.cpac_pipeline.run(\\\"%s\\\",\\\"%s\\\",\\\"${PBS_ARRAYID}\\\",\\\"%s\\\", \\\"%s\\\" , \\\"%s\\\", \\\"%s\\\", \\\"%s\\\") \" " % (str(config_file), \
subject_list_file, strategies_file, c.maskSpecificationFile, c.roiSpecificationFile, c.templateSpecificationFile, p_name), file=f)
# print >>f, "python -c \"import CPAC; CPAC.pipeline.cpac_pipeline.py -c %s -s %s -indx ${PBS_ARRAYID} -strategies %s \" " %(str(config_file), subject_list_file, strategies_file)
#print >>f, "python CPAC.pipeline.cpac_pipeline.py -c ", str(config_file), "-s ", subject_list_file, " -indx ${PBS_ARRAYID} -strategies ", strategies_file
f.close()
subprocess.getoutput('chmod +x %s' % subject_bash_file )
示例5: menu
def menu():
requestMenu = subprocess.getoutput("echo `zenity --list --title='PTTP' --text='What type of request do you want to make?' --column='Request type' 'GET' 'POST'`")
requestMenu = requestMenu.split("\n")
requestMenu = requestMenu[len(requestMenu) - 1]
if requestMenu == "GET":
#Do a GET request
getMenu = subprocess.getoutput("echo `zenity --list --title='PTTP' --text='Authentication/response:' --column='Option' 'No authentication' 'Basic authentication' 'No authentication (plain text)' 'Basic authentication (plain text)'`")
getMenu = getMenu.split("\n")
getMenu = getMenu[len(getMenu) - 1]
try:
get(getMenu)
except(urllib.error.HTTPError, urllib.error.URLError) as error:
os.system("zenity --error --title='PTTP' --text='"+format(error)+"'")
except:
os.system("zenity --error --title='PTTP' --text='Oops! There was an error in your request.'")
elif requestMenu == "POST":
#Do a POST request
postMenu = subprocess.getoutput("echo `zenity --list --title='PTTP' --text='Authentication/response:' --column='Option' 'No authentication' 'Basic authentication' 'No authentication (plain text)' 'Basic authentication (plain text)'`")
postMenu = postMenu.split("\n")
postMenu = postMenu[len(postMenu) - 1]
try:
post(postMenu)
except(urllib.error.HTTPError, urllib.error.URLError) as error:
os.system("zenity --error --title='PTTP' --text='"+format(error)+"'")
except:
os.system("zenity --error --title='PTTP' --text='Oops! There was an error in your request.'")
else:
sys.exit()
示例6: _learn
def _learn(self, irc, msg, channel, text, probability):
"""Internal method for learning phrases."""
if os.path.exists(self._getBrainDirectoryForChannel(channel)):
# Does this channel have a directory for the brain file stored and does this file exist?
text = self._cleanText(text)
if text and len(text) > 1 and not text.isspace():
self.log.debug("Learning: {0}".format(text))
cobeBrain = Brain(self._getBrainDirectoryForChannel(channel))
cobeBrain.learn(text)
if random.randint(0, 10000) <= probability:
self._reply(irc, msg, channel, text)
else: # Nope, let's make it!
subprocess.getoutput('{0} {1}'.format(self._doCommand(channel), 'init'))
text = self._cleanText(text)
if text and len(text) > 1 and not text.isspace():
self.log.debug("Learning: {0}".format(text))
cobeBrain = Brain(self._getBrainDirectoryForChannel(channel))
cobeBrain.learn(text)
if random.randint(0, 10000) <= probability:
self._reply(irc, msg, channel, text)
示例7: _update_repos
def _update_repos(self):
'''
Prepare the reposiroties, return dict with repo information:
{'<repo dir>': {'last_rev': '<last revision number>',
'files': '<list of files changed since last revision>'}
'''
repo_info = {}
for base in self.roots:
repo_info[base] = {}
if not os.path.isdir(base):
# checkout the repo
co_cmd = 'svn co ' + self.roots[base] + ' ' + base
lines = bytes.decode(subprocess.getoutput(co_cmd)).splitlines()
repo_info[base]['last_rev'] = None
repo_info[base]['files'] = self._find_pkgbuilds(base, lines)
else:
# Check the release numbers and run an update
l_cmd = 'svn info ' + base + " | grep Revision: | awk '{print $2}'"
l_rev = int(subprocess.getoutput(i_cmd).strip())
repo_info['last_rev'] = str(l_rev)
r_cmd = 'svn info ' + self.roots[base] + " | grep Revision: | awk '{print $2}'"
r_rev = int(subprocess.getoutput(r_cmd).strip())
if r_rev > l_rev:
# The local repo is out of date, update!
u_cmd = 'svn up ' + base
lines = bytes.decode(subprocess.getoutput(u_cmd)).splitlines()
repo_info[base]['files'] = self._find_pkgbuilds(base, lines)
return repo_info
示例8: _resolution
def _resolution(self):
width=0
heigth=0
if(SystemInformations._platform(self) != "Windows"):
resolution = str(subprocess.getoutput("xrandr | grep connected"))
resolution = re.sub("[a-z]*-[0-9]*", "", resolution)
resolution = re.sub("\).*", "", resolution)
resolution = re.sub("\+.* ", "", resolution)
resolution = re.sub("[^0-9^\n]*", "", resolution)
parseResolution = resolution.split("\n")
for x in range(0, len(parseResolution)):
if(width != 0):
if(parseResolution[x][0:4] != ""):
width=width+int(parseResolution[x][0:4])
else:
if(parseResolution[x][0:4] != ""):
width=int(parseResolution[x][0:4])
if(heigth != 0):
if(parseResolution[x][4:9] != ""):
if(heigth < int(parseResolution[x][4:9])):
heigth = int(parseResolution[x][4:9])
else:
if(parseResolution[x][4:9] != ""):
heigth=int(parseResolution[x][4:9])
else:
resolution=re.sub("\n","",subprocess.getoutput("wmic path Win32_VideoController get CurrentHorizontalResolution,CurrentVerticalResolution"))
resolution=re.sub(" *","",resolution)
resolution=re.sub("CurrentHorizontalResolution","",resolution)
resolution=re.sub("CurrentVerticalResolution","",resolution)
width=int(resolution[0:4])
heigth=int(resolution[4:8])
totalResolution = str(width)+"x"+str(heigth)
return totalResolution
示例9: test_nfs_getfacl
def test_nfs_getfacl():
# mesures sur le getfacl
test = RandomGen()
path = '/mnt/nfs/test-acl' # NFS mounted directory
u = subprocess.getoutput('rm ' + path + "/*") # clean directory
print("test acl getfacl\n")
f = open('/tmp/acl-result-getfacl','w')
for i in range(37):
test.getUserList()
testfile = 'testfile' + str(i)
u = subprocess.getoutput('touch ' + path + "/" + testfile)
print("setfacl " + str(i) + " " + u)
for j in range(i):
user = test.uList.pop()
mode = test.createRandomMode()
u = subprocess.getoutput('setfacl -m u:' + user + ':' + mode + " " + path + "/" + testfile)
t1=time.time()
u = subprocess.getoutput('getfacl ' + path + "/" + testfile)
print("getfacl - " + str(i) + u + "\n")
t2=time.time()
f.write(str(i) + "\t" + str(t2-t1)+"\n")
f.close()
示例10: library_install_objdump
def library_install_objdump(path, level):
if path in skip_libs or path in done:
return
if level > 0:
lib = find_dll(path)
if lib == "": # not found
skip_libs.append(path)
print("Not found: " + path)
return
print(lib)
subprocess.getoutput("cp " + lib + " " + build_path)
else:
print("Processing target " + path)
lib = path
done.append(path)
command = objdump_path + " -p " + lib + " | grep -o ': .*\.dll$'"
res = subprocess.getstatusoutput(command)
if (res[0] > 0):
print("Error: objdump failed with " + lib)
else:
dlls = subprocess.getoutput(command).split("\n")
for line in dlls:
dll = (line.split(": "))[1]
if dll not in done and dll not in skip_libs:
level += 1
library_install_objdump(dll, level)
示例11: test_acl_default
def test_acl_default(path):
# set default acl on the test directory
u = subprocess.getoutput('mkdir ' + path + "/" + testdir)
u = subprocess.getoutput('getfacl ' + path + "/" + testdir)
acl=[]
for i in range (len(splitedresult)-1):
splitedline = splitedresult[i].split('::')
name = splitedline[0]
entry = splitedline[1]
acl.append(name,entry)
# create a file in this directory
u = subprocess.getoutput('touch ' + path + "/" + testdir + testfile)
# get the file's ACL and verify
u = subprocess.getoutput('getfacl ' + path + "/" + testdir + testfile)
splitedresult = u.split('\n')
acl2=[]
for i in range (len(splitedresult)-1):
splitedline = splitedresult[i].split('::')
name = splitedline[0]
entry = splitedline[1]
acl2.append(name,entry)
result_final = True
while i < len(acl2):
result = False
while j < len(acl2) and result == False:
if acl2[i] == acl[j]:
result = True
if result == False:
result_final = False
示例12: restruct_linux
def restruct_linux():
qmake = sys.argv[3]
# Copy the entire directory
for d in ['bin', 'lib', 'libexec', 'share']:
shutil.copytree(os.path.join(app_bundle, d), os.path.join(target_path, d), symlinks=True)
# Copy Qt libs
qtlibs_dir = subprocess.getoutput('%s -query QT_INSTALL_LIBS' % qmake).strip()
for lib in ['Core', 'Gui', 'Widgets', 'Concurrent', 'Network', 'PrintSupport',
'Qml', 'Quick', 'QuickWidgets', 'Xml', 'Svg', 'XcbQpa', 'Sql']:
shutil.copy(os.path.join(qtlibs_dir, 'libQt5%s.so.5'%lib), lib_dir)
# Copy Qt plugins
qtplugins_dir = subprocess.getoutput('%s -query QT_INSTALL_PLUGINS' % qmake).strip()
os.makedirs(plugins_dir)
for plugin in ['bearer', 'designer', 'iconengines', 'imageformats',
'platforms', 'sqldrivers', 'xcbglintegrations']:
shutil.copytree(os.path.join(qtplugins_dir, plugin), os.path.join(plugins_dir, plugin))
# Copy QtQuick modules
qtqml_dir = subprocess.getoutput('%s -query QT_INSTALL_QML' % qmake).strip()
shutil.copytree(qtqml_dir, qml_dir)
# Fix qt.conf
open(os.path.join(bin_dir, 'qt.conf'), 'w').write('[Paths]\nPrefix = ..\n')
open(os.path.join(libexec_dir, 'qtcreator', 'qt.conf'), 'w').write('[Paths]\nPrefix = ../..\n')
# Fix rpath of qtcreator and executibles under libexec
cmd = "chrpath -r '$ORIGIN/../lib/qtcreator:$ORIGIN/../lib:' " + os.path.join(bin_dir, 'qtcreator')
os.system(cmd)
for f in os.listdir(os.path.join(libexec_dir, 'qtcreator')):
cmd = "chrpath -r '$ORIGIN/../../lib/qtcreator:$ORIGIN/../../lib:' " + os.path.join(libexec_dir, 'qtcreator', f)
os.system(cmd)
示例13: main
def main():
print('Strated ---------------------')
# execute(['ls', '-ls'])
# proc = subprocess.Popen(['ls -lsa'], stdout = subprocess.PIPE, shell = True)
# (out, err) = proc.communicate()
# proc_status = proc.wait()
# print("Command exit status: " + str(proc_status))
# print("Command output: " + str(out))
# output = subprocess.check_output('ls -ls', shell = True)
# print(output)
ip = '178.62.18.112'
cmd = 'ssh-keygen -f ~/.ssh/known_hosts -R ' + ip
print('CMD [' + cmd + ']')
stdoutdata = subprocess.getoutput(cmd)
print('------- OUTPUT START --------')
print(stdoutdata)
print('======= OUTPUT END ========')
cmd = 'echo -e \"Host ${myvmip}\n\tStrictHostKeyChecking no\n\" >> ~/.ssh/config'
print('CMD [' + cmd + ']')
stdoutdata = subprocess.getoutput(cmd)
print('------- OUTPUT START --------')
print(stdoutdata)
print('======= OUTPUT END ========')
# s = pxssh.pxssh()
# s.login()
print('Finished --------------------')
示例14: GetProtoRuleFormattedData
def GetProtoRuleFormattedData(cls, rule_data, out_type):
"""Get the formatted proto dependency info for the output type.
Args:
rule_data: dict: The rule data for the proto rule.
out_type: string: The type for which the proto data is to be generated.
Return:
dict: Corresponding rules generated for the out_type.
"""
srcs = rule_data.get('src', set())
protobuf_base_dir = cls.GetProtoBufBaseDir();
out = {}
if out_type.find('cc_') == 0 : # Generated cc rule.
pkg_config_cmd = ('export PKG_CONFIG_PATH=%s; '
'pkg-config --define-variable=prefix=%s protobuf' %
(os.path.join(protobuf_base_dir, 'lib/pkgconfig'), protobuf_base_dir))
out['src'] = set([ cls.__GetOutFileName(x, '.pb.cc') for x in srcs ])
out['hdr'] = set([ cls.__GetOutFileName(x, '.pb.h') for x in srcs ])
out['flag'] = set(subprocess.getoutput(pkg_config_cmd + ' --cflags').split())
out['link'] = set(subprocess.getoutput(pkg_config_cmd + ' --libs').split())
else:
TermColor.Error('Unsupported referrer type %s' % out_type)
return out
示例15: tmux_layout
def tmux_layout():
"""Layout for gdb-dashboard using tmux panes"""
# Bug? Cursor (in the terminal) is gone in any tmux pane after this function.
panes_tty = subprocess.getoutput(["tmux lsp -F'#{pane_tty}'"]).split('\n')
panes_id = subprocess.getoutput(["tmux lsp -F'#{pane_id}'"]).split('\n')
print("panes_tty =", panes_tty)
if len(panes_tty) == 2:
# Put the outout in the right pane, and enable history and stacklocals
gdb.execute("dashboard -layout !stacklocals stack history !threads source")
# gdb.execute("dashboard -output " + panes_tty[1])
# gdb.execute("dashboard stacklocals -output " + panes_tty[1])
right_tty = panes_tty[1]
gdb.execute("dashboard stack -output " + right_tty)
gdb.execute("dashboard history -output " + right_tty)
gdb.execute("dashboard source -output " + right_tty)
if len(panes_tty) == 3:
# NOTE: Execute tmux_split_gdb (from ~/.tmux_utils)
gdb.execute("dashboard -layout stacklocals stack history !threads source")
# gdb.execute("dashboard -output " + panes_tty[1])
right_tty = panes_tty[2]
up_index = 0
up_tty = panes_tty[up_index]
gdb.execute("dashboard stacklocals -output " + right_tty)
gdb.execute("dashboard stack -output " + right_tty)
gdb.execute("dashboard history -output " + right_tty)
gdb.execute("dashboard source -output " + up_tty)
pane_source_height = subprocess.getoutput(["tmux lsp -F'#{pane_height}'"]).split('\n')[up_index]
gdb.execute("dashboard source -style context " + str(int(int(pane_source_height)/2.1)))