16.1. os
— Diversas interfaces de sistema operacional¶
Código fonte: Lib/os.py
Este módulo fornece uma maneira simples de usar funcionalidades que são dependentes de sistema operacional. Se desejar ler ou escrever um arquivo, veja open()
; se o que quer é manipular estruturas de diretórios, veja o módulo os.path
; e se quiser ler todas as linhas, de todos os arquivos, na linha de comando, veja o módulo fileinput
. Para criar arquivos e diretórios temporários, veja o módulo tempfile
; e, para manipulação em alto nível de arquivos e diretórios, veja o módulo shutil
.
Notas sobre a disponibilidade dessas funções:
- O modelo dos módulos dependentes do sistema operacional embutidos no Python é tal que, desde que a mesma funcionalidade esteja disponível, a mesma interface é usada; por exemplo, a função
os.stat(path)
retorna informações estatísticas sobre path no mesmo formato (que é originado com a interface POSIX). - Extensões específicas a um sistema operacional também estão disponíveis através do módulo: mod:os, mas usá-las é, naturalmente, uma ameaça à portabilidade.
- Todas as funções que aceitam nomes de caminhos ou arquivos, aceitam objetos bytes e string, e resultam em um objeto do mesmo tipo, se um caminho ou nome de arquivo for retornado.
- Uma nota “Disponibilidade: Unix” significa que essa função é comumente encontrada em sistemas Unix. Não faz nenhuma reivindicação sobre sua existência em um sistema operacional específico.
- <br>
Nota
Todas as funções nesse módulo levantam a exceção OSError
, no caso de nomes e caminhos de arquivos inválidos ou inacessíveis, ou no caso de outros argumentos que possuem o tipo correto, mas não são aceitos pelo sistema operacional.
-
os.
name
¶ The name of the operating system dependent module imported. The following names have currently been registered:
'posix'
,'nt'
,'ce'
,'java'
.Ver também
sys.platform
tem uma granularidade mais fina.os.uname()
fornece informação de versões dependentes do sistema.O módulo
platform
fornece verificações detalhadas sobre a identificação do sistema.
16.1.1. Nomes de arquivos, argumentos de linha de comando e variáveis de ambiente¶
Em Python, nomes de arquivos, argumentos de linha de comando e variáveis de ambiente são representados usando o tipo string. Em alguns sistemas, é necessária a decodificação dessas seqüências de caracteres, de e para bytes, antes de transmiti-las ao sistema operacional. O Python usa a codificação do sistema de arquivos para realizar essa conversão (consulte sys.getfilesystemencoding()
).
Alterado na versão 3.1: Em alguns sistemas a conversão, usando a codificação do sistema de arquivos, pode falhar. Neste caso, o Python usa o surrogateescape encoding error handler, o que significa que bytes não decodificados são substituídos por um caractere Unicode U+DCxx na decodificação, e estes são novamente traduzidos para o byte original na codificação.
A codificação do sistema de arquivos deve garantir a decodificação bem-sucedida de todos os bytes abaixo de 128. Se a codificação do sistema de arquivos não fornecer essa garantia, as funções da API poderão gerar UnicodeErrors.
16.1.2. Parâmetros de Processo¶
Essas funções e itens de dados fornecem informações e operam no processo e usuário atuais.
-
os.
ctermid
()¶ Retorna o nome do arquivo correspondente ao terminal de controle do processo.
Disponibilidade: Unix.
-
os.
environ
¶ Um objeto mapping representando uma string do ambiente. Por exemplo,
environ['HOME']
é o nome do caminho do seu diretório pessoal (em algumas plataformas), e é equivalente agetenv("HOME")
em C.Este mapeamento é capturado na primeira vez que o módulo
os
é importado, normalmente durante a inicialização do Python, como parte do processamento do arquivosite.py
. Mudanças no ambiente feitas após esse momento não são refletidas emos.environ
, exceto pelas mudanças feitas modificandoos.environ
diretamente.Se a plataforma suportar a função
putenv()
, esse mapeamento pode ser usado para modificar o ambiente, além de consultá-lo.putenv()
será chamado automaticamente quando o mapeamento for modificado.No Unix, chaves e valores usam
sys.getfilesystemencoding()
e o manipulador de erros'surrogateescape'
. Useenvironb
se quiser usar uma codificação diferente.Nota
Chamar a função
putenv()
diretamente não mudaos.environ
, por isso é melhor modificaros.environ
.Nota
Em algumas plataformas, incluindo FreeBSD e Mac OS X, a modificação de
environ
pode causar vazamentos de memória. Consulte a documentação do sistema paraputenv()
.Se a função
putenv()
não for fornecida, uma cópia modificada desse mapeamento pode ser passada para as funções apropriadas de criação de processos, para fazer com que os processos filhos usem um ambiente modificado.Se a plataforma suportar a função
unsetenv()
, os itens nesse mapeamento poderão ser excluídos para remover variáveis de ambiente.unsetenv()
será chamado automaticamente quando um item é excluído deos.environ
, e quando um dos métodospop()
ouclear()
é chamado.
-
os.
environb
¶ Versão bytes
environ
: um objeto mapping representando o ambiente como byte strings.environ
eenvironb
são sincronizados (modificarenvironb
atualizaenviron
, e vice versa).environb
só está disponível sesupports_bytes_environ
for True.Novo na versão 3.2.
-
os.
chdir
(path) -
os.
fchdir
(fd) -
os.
getcwd
() Essas funções são descritas em: Arquivos e Diretórios.
-
os.
fsencode
(filename)¶ Encode filename to the filesystem encoding with
'surrogateescape'
error handler, or'strict'
on Windows; returnbytes
unchanged.fsdecode()
é a função reversa.Novo na versão 3.2.
-
os.
fsdecode
(filename)¶ Decode filename from the filesystem encoding with
'surrogateescape'
error handler, or'strict'
on Windows; returnstr
unchanged.fsencode()
é a função reversa.Novo na versão 3.2.
-
os.
getenv
(key, default=None)¶ Retorna o valor da variável de ambiente key se existir, ou default, se não. key, default e o resultado são str.
No Unix, chaves e valores são decodificados com a função
sys.getfilesystemencoding()
e o o manipulador de erros'surrogateescape'
. Useos.getenvb()
se quiser usar uma codificação diferente.Disponibilidade: a maioria dos sabores de Unix, Windows.
-
os.
getenvb
(key, default=None)¶ Retorna o valor da variável de ambiente key, se existir, ou default, se não existir. key, default e o resultado são bytes.
getenvb()
só estará disponível sesupports_bytes_environ
for True.Disponibilidade: maioria das distribuições Unix.
Novo na versão 3.2.
-
os.
get_exec_path
(env=None)¶ Retorna a lista de diretórios que serão buscados por um executável nomeado, semelhante a um shell, ao iniciar um processo. env, quando especificado, deve ser um dicionário de variáveis de ambiente para procurar o PATH. Por padrão, quando env é
None
,environ
é usado.Novo na versão 3.2.
-
os.
getegid
()¶ Retorna o efetivo ID do grupo do processo atual. Isso corresponde ao bit “set id” no arquivo que está sendo executado no processo atual.
Disponibilidade: Unix.
-
os.
geteuid
()¶ Retorna o efetivo ID de usuário do processo atual.
Disponibilidade: Unix.
-
os.
getgid
()¶ Retorna o ID real do grupo do processo atual.
Disponibilidade: Unix.
-
os.
getgrouplist
(user, group)¶ Retornar lista de IDs de grupos aos quais user pertence. Se group não estiver na lista, será incluído; normalmente, group é especificado como o campo de ID do grupo, a partir do registro de senha para user.
Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
getgroups
()¶ Retorna a lista de IDs de grupos suplementares associados ao processo atual.
Disponibilidade: Unix.
Nota
No Mac OS X, o comportamento da função
getgroups()
difere um pouco de outras plataformas Unix. Se o interpretador Python foi compilado para distribuição na versão10.5
ou anterior,getgroups()
retorna a lista de ids de grupos efetivos, associados ao processo de usuário atual; esta lista é limitada a um número de entradas definido pelo sistema, tipicamente 16, e pode ser modificada por chamadas parasetgroups()
se tiver o privilégio adequado. Se foi compilado para distribuição na versão maior que10.5
,getgroups()
retorna a lista de acesso de grupo atual para o usuário associado ao id de usuário efetivo do processo; a lista de acesso de grupo pode mudar durante a vida útil do processo, e ela não é afetada por chamadas parasetgroups()
, e seu comprimento não é limitado a 16. O valor da constanteMACOSX_DEPLOYMENT_TARGET
, pode ser obtido comsysconfig.get_config_var()
.
-
os.
getlogin
()¶ Return the name of the user logged in on the controlling terminal of the process. For most purposes, it is more useful to use the environment variables
LOGNAME
orUSERNAME
to find out who the user is, orpwd.getpwuid(os.getuid())[0]
to get the login name of the current real user id.Disponibilidade: Unix, Windows.
-
os.
getpgid
(pid)¶ Retorna o ID do grupo de processo com pid. Se pid for 0, o ID do grupo do processo atual é retornado.
Disponibilidade: Unix.
-
os.
getpgrp
()¶ Retorna o ID do grupo de processo atual.
Disponibilidade: Unix.
-
os.
getpid
()¶ Retorna o id do processo atual.
-
os.
getppid
()¶ Retorna o ID do processo pai. Quando o processo pai é encerrado, no Unix, o ID retornado é o do processo init(1); no Windows, ainda é o mesmo ID, que já pode ser reutilizado por outro processo.
Disponibilidade: Unix, Windows.
Alterado na versão 3.2: Adicionado suporte para Windows.
-
os.
getpriority
(which, who)¶ Obtém prioridade de agendamento de programa. O valor which é um entre
PRIO_PROCESS
,PRIO_PGRP
ouPRIO_USER
, e who é interpretado em relação a which (um identificador de processo paraPRIO_PROCESS
, identificador do grupo de processos paraPRIO_PGRP
e um ID de usuário paraPRIO_USER
). Um valor zero para who indica (respectivamente) o processo de chamada, o grupo de processos do processo de chamada ou o ID do usuário real do processo de chamada.Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
PRIO_PROCESS
¶ -
os.
PRIO_PGRP
¶ -
os.
PRIO_USER
¶ Parâmetros para as funções
getpriority()
esetpriority()
.Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
getresuid
()¶ Retorna uma tupla (ruid, euid, suid) indicando os IDs de usuário reais, efetivos e salvos do processo atual.
Disponibilidade: Unix.
Novo na versão 3.2.
-
os.
getresgid
()¶ Retorna uma tupla (rgid, egid, sgid) indicando os IDs de grupo reais, efetivos e salvos do processo atual.
Disponibilidade: Unix.
Novo na versão 3.2.
-
os.
getuid
()¶ Retorna o ID de usuário real do processo atual.
Disponibilidade: Unix.
-
os.
initgroups
(username, gid)¶ Chama o initgroups() do sistema para inicializar a lista de acesso ao grupo com todos os grupos dos quais o nome de usuário especificado é membro, mais o ID do grupo especificado.
Disponibilidade: Unix.
Novo na versão 3.2.
-
os.
putenv
(key, value)¶ Define a variável de ambiente denominada key como a string value. Tais mudanças no ambiente afetam os subprocessos iniciados com
os.system()
,popen()
oufork()
andexecv()
.Disponibilidade: a maioria dos sabores de Unix, Windows.
Nota
Em algumas plataformas, incluindo FreeBSD e Mac OS X, a configuração
environ
pode causar vazamento de memória. Consulte a documentação do sistema para putenv.Quando há suporte a
putenv()
, as atribuições para itens emos.environ
são automaticamente convertidas em chamadas correspondentes paraputenv()
; no entanto, chamadas paraputenv()
não atualizaos.environ
, então é realmente preferível atribuir itens aos.environ
.
-
os.
setegid
(egid)¶ Define o ID do grupo efetivo do processo atual.
Disponibilidade: Unix.
-
os.
seteuid
(euid)¶ Define o ID de usuário efetivo do processo atual.
Disponibilidade: Unix.
-
os.
setgid
(gid)¶ Define o ID do grupo do processo atual.
Disponibilidade: Unix.
-
os.
setgroups
(groups)¶ Define a lista de IDs de grupo suplementares associados ao processo atual como groups. groups deve ser uma sequência e cada elemento deve ser um número inteiro identificando um grupo. Esta operação normalmente está disponível apenas para o superusuário.
Disponibilidade: Unix.
Nota
No Mac OS X, o tamanho de groups não pode exceder o número máximo definido pelo sistema de IDs de grupo efetivos, normalmente 16. Consulte a documentação de
getgroups()
para casos em que ele pode não retornar o mesmo conjunto de listas de grupos chamando setgroups().
-
os.
setpgrp
()¶ Executa a chamada de sistema
setpgrp()
ousetpgrp (0, 0)
dependendo da versão implementada (se houver). Veja o manual do Unix para a semântica.Disponibilidade: Unix.
-
os.
setpgid
(pid, pgrp)¶ Faz a chamada de sistema
setpgid()
para definir o ID do grupo do processo com pid para o grupo de processos com o id pgrp. Veja o manual do Unix para a semântica.Disponibilidade: Unix.
-
os.
setpriority
(which, who, priority)¶ Define a prioridade de agendamento de programa. O valor which é um entre
PRIO_PROCESS
,PRIO_PGRP
ouPRIO_USER
, e who é interpretado em relação a which (um identificador de processo paraPRIO_PROCESS
, identificador do grupo de processos paraPRIO_PGRP
e um ID de usuário paraPRIO_USER
). Um valor zero para who indica (respectivamente) o processo de chamada, o grupo de processos do processo de chamada ou o ID do usuário real do processo de chamada. priority é um valor na faixa de -20 a 19. A prioridade padrão é 0; prioridades menores resultam em agendamento um mais favorável.Disponibilidade: Unix
Novo na versão 3.3.
-
os.
setregid
(rgid, egid)¶ Define os IDs de grupo real e efetivo do processo atual
Disponibilidade: Unix.
-
os.
setresgid
(rgid, egid, sgid)¶ Define os IDs de grupo real, efetivo e salvo do processo atual
Disponibilidade: Unix.
Novo na versão 3.2.
-
os.
setresuid
(ruid, euid, suid)¶ Define os IDs de usuário real, efetivo e salvo do processo atual
Disponibilidade: Unix.
Novo na versão 3.2.
-
os.
setreuid
(ruid, euid)¶ Define os IDs de usuário real e efetivo do processo atual.
Disponibilidade: Unix.
-
os.
getsid
(pid)¶ Executa a chamada de sistema
getsid()
. Veja o manual do Unix para semântica.Disponibilidade: Unix.
-
os.
setsid
()¶ Executa a chamada de sistema
setsid()
. Veja o manual do Unix para semântica.Disponibilidade: Unix.
-
os.
setuid
(uid)¶ Define o ID de usuário do processo atual.
Disponibilidade: Unix.
-
os.
strerror
(code)¶ Retorna a mensagem de erro correspondente ao código de erro em code. Nas plataformas em que
strerror()
retornaNULL
quando recebe um número de erro desconhecido,ValueError
é gerada.
-
os.
supports_bytes_environ
¶ True
se o tipo de sistema operacional nativo do ambiente estiver em bytes (ex.,False
no Windows).Novo na versão 3.2.
-
os.
umask
(mask)¶ Define o umask numérico atual e retorna o umask anterior.
-
os.
uname
()¶ Retorna informações identificando o sistema operacional atual. O valor retornado é um objeto com cinco atributos.
sysname
- nome do sistema operacionalnodename
- nome da máquina na rede (definido pela implementação)release
- versão do sistema operacionalversion
- versão do sistema operacionalmachine
- identificador de hardware
Para compatibilidade com versões anteriores, esse objeto também é iterável, comportando-se como uma cinco tupla contendo
sysname
,nodename
,release
,version
emachine
nessa ordem.Alguns sistemas truncam
nodename
para 8 caracteres ou para o componente principal; uma maneira melhor de obter o nome do host ésocket.gethostname()
ou até mesmosocket.gethostbyaddr(socket.gethostname())
.Disponibilidade: distribuicões recentes de Unix
Alterado na versão 3.3: Retorna tupla alterada de uma tupla para um objeto tipo tupla com atributos nomeados.
-
os.
unsetenv
(key)¶ Cancela (exclui) a variável de ambiente denominada key. Tais mudanças no ambiente afetam subprocessos iniciados com
os.system()
,popen()
oufork()
eexecv()
.Quando
unsetenv()
é suportado, a exclusão de itens emos.environ
é automaticamente traduzida para uma chamada correspondente aunsetenv()
; no entanto, chamadas aunsetenv()
não atualizamos.environ
, por isso, na verdade é preferível excluir itens deos.environ
.Disponibilidade: a maioria dos sabores de Unix, Windows.
16.1.3. Criação de Objetos Files¶
This function creates new file objects. (See also
open()
for opening file descriptors.)
16.1.4. Operações dos Descritores de Arquivos¶
Estas funções operam em fluxos de E/S referenciados usando descritores de arquivos.
Descritores de arquivos são pequenos números inteiros correspondentes a um arquivo que foi aberto pelo processo atual. Por exemplo, a entrada padrão geralmente é o descritor de arquivo 0, a saída padrão 1 e erro padrão 2. Outros arquivos abertos por um processo serão então atribuídos 3, 4, 5, e assim por diante. O nome “descritor de arquivo” é um pouco enganoso; em plataformas UNIX, sockets e pipes também são referenciados como descritores de arquivos.
O método fileno()
pode ser usado para obter o descritor de arquivo associado a um file object quando solicitado. Note-se que usar o descritor de arquivo diretamente ignorará os métodos do objeto de arquivo, ignorando aspectos como buffer interno de dados.
-
os.
closerange
(fd_low, fd_high)¶ Feche todos os descritores de arquivo de fd_low (inclusivo) a fd_high (exclusivo), ignorando erros. Equivalente a (mas muito mais rápido do que):
for fd in range(fd_low, fd_high): try: os.close(fd) except OSError: pass
-
os.
device_encoding
(fd)¶ Retorna uma string descrevendo a codificação do dispositivo associado a fd se estiver conectado a um terminal; senão retorna
None
.
-
os.
dup
(fd)¶ Retorna uma cópia do descritor de arquivo fd. O novo descritor de arquivo é non-inheritable.
No Windows, ao duplicar um fluxo padrão (0: stdin, 1: stdout, 2: stderr), o novo descritor de arquivo é inheritable.
Alterado na versão 3.4: O novo descritor de arquivo agora é não-hereditário.
-
os.
dup2
(fd, fd2, inheritable=True)¶ Duplicate file descriptor fd to fd2, closing the latter first if necessary. The file descriptor fd2 is inheritable by default, or non-inheritable if inheritable is
False
.Alterado na versão 3.4: Adicionar o parâmetro opcional inheritable.
-
os.
fchmod
(fd, mode)¶ Altera o modo do arquivo dado por fd ao mode numérico. Veja a documentação de
chmod()
para valores possíveis de mode. A partir do Python 3.3, isto é equivalente aos.chmod(fd, mode)
.Disponibilidade: Unix.
-
os.
fchown
(fd, uid, gid)¶ Altera o o ID do proprietário e do grupo do arquivo dado por fd para o uid e gid numérico. Para deixar um dos ids inalteradas, defina-o como -1. Veja
chown()
. A partir do Python 3.3, isto é equivalente aos.chown(fd, uid, gid)
.Disponibilidade: Unix.
-
os.
fdatasync
(fd)¶ Força de gravação de arquivo com descritor de arquivo fd no disco. Não força a atualização de metadados.
Disponibilidade: Unix.
Nota
Esta função não está disponível no MacOS.
-
os.
fpathconf
(fd, name)¶ Retorna informações de configuração de sistema relevantes para um arquivo aberto. name especifica o valor de configuração para recuperar; pode ser uma string que é o nome de um valor do sistema definido; estes nomes são especificados em uma série de padrões (POSIX.1, Unix 95, Unix 98 e outros). Algumas plataformas definem nomes adicionais também. Os nomes conhecidos do sistema operacional hospedeiro são dadas no dicionário
pathconf_names
. Para variáveis de configuração não incluídas neste mapeamento, também é aceito passar um número inteiro para name.Se name for uma string e não for conhecida,
ValueError
é gerado. Se um valor específico para name não for compatível com o sistema de host, mesmo que seja incluído nopathconf_names
, um erroOSError
é gerado comerrno.EINVAL
como número do erro.Assim como no Python 3.3, é equivalente a
os.pathconf(fd, name)
.Disponibilidade: Unix.
-
os.
fstat
(fd)¶ Captura o status do descritor de arquivo fd. Retorna um objeto
stat_result
.Assim como no Python 3.3, é equivalente a
os.stat(fd)
.Ver também
A função
stat()
.
-
os.
fstatvfs
(fd)¶ Retorna informações sobre o sistema de arquivos que contém o arquivo associado com descritor de arquivo fd, como
statvfs()
. A partir do Python 3.3, isso equivale aos.statvfs(fd)
.Disponibilidade: Unix.
-
os.
fsync
(fd)¶ Gravação à força no disco de arquivo com descritor de arquivo fd. No Unix, isto chama a função nativa
fsync()
; no Windows, a função de MS_commit()
.Se você estiver começando com buffer no Python file object f, primeiro use
f.flush()
, e depois useos.fsync(f.fileno())
, para garantir que todos os buffers internos associados com f sejam gravados no disco.Disponibilidade: Unix, Windows.
-
os.
ftruncate
(fd, length)¶ Trunca o arquivo correspondente ao descritor de arquivo fd, de modo que tenha no máximo length bytes de tamanho. A partir do Python 3.3, isto é equivalente a
os.truncate(fd, length)
.Disponibilidade: Unix, Windows.
Alterado na versão 3.5: Adicionado suporte para o Windows.
-
os.
get_blocking
(fd)¶ Obtém o modo de bloqueio do descritor de arquivo:
False
se o flagO_NONBLOCK
estiver marcado,True
se o flag estiver desmarcado.Veja também
set_blocking()
esocket.socket.setblocking()
.Disponibilidade: Unix.
Novo na versão 3.5.
-
os.
isatty
(fd)¶ Retorna
True
se o descritor de arquivo fd estiver aberto e conectado a um dispositivo do tipo tty, senãoFalse
.
-
os.
lockf
(fd, cmd, len)¶ Aplica, testa ou remove um bloqueio POSIX em um descritor de arquivo aberto. fd é um descritor de arquivo aberto. cmd especifica o comando a ser usado - um dentre
F_LOCK
,F_TLOCK
,F_ULOCK
ouF_TEST
. len especifica a seção do arquivo a ser bloqueada.Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
F_LOCK
¶ -
os.
F_TLOCK
¶ -
os.
F_ULOCK
¶ -
os.
F_TEST
¶ Flags que especificam qual ação
lockf()
vai realizar.Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
lseek
(fd, pos, how)¶ Define a posição atual do descritor de arquivo fd para a posição pos, modificada por how:
SEEK_SET
ou0
para definir a posição em relação ao início do arquivo;SEEK_CUR
ou1
para defini-la em relação à posição atual;SEEK_END
ou2
para defini-la em relação ao final do arquivo. Retorna a nova posição do cursor em bytes, a partir do início.
-
os.
SEEK_SET
¶ -
os.
SEEK_CUR
¶ -
os.
SEEK_END
¶ Parâmetros para a function
lseek()
. Seus valores são respectivamente 0, 1, e 2.Novo na versão 3.3: Alguns sistemas operacionais podem suportar valores adicionais, como
os.SEEK_HOLE
ouos.SEEK_DATA
.
-
os.
open
(path, flags, mode=0o777, *, dir_fd=None)¶ Abre o arquivo path e define várias flags de acordo com flags e, possivelmente, seu modo, de acordo com mode. Ao computar mode, o valor atual de umask é iniciar com máscara. Retorna o descritor de arquivo para o arquivo recém-aberto. O novo descritor de arquivo é non-inheritable.
Para ler uma descrição dos valores de flags e modos, veja a documentação de tempo de execução C; constantes de flag (como
O_RDONLY
eO_WRONLY
) são definidas no móduloos
. Em particular, no Windows é necessário adicionarO_BINARY
para abrir arquivos em modo binário.Esta função pode suportar paths relative to directory descriptors com o parâmetro dir_fd.
Alterado na versão 3.4: O novo descritor de arquivo agora é não-hereditário.
Nota
Esta função é destinada a E/S de baixo nível. Para uso normal, use a função embutida
open()
, que retorna um file object com os métodosread()
ewrite()
(e muitos mais). Para envolver um descritor de arquivo em um objeto de arquivo, usefdopen()
.Novo na versão 3.3: O argumento dir_fd.
Alterado na versão 3.5: Se a chamada de sistema é interrompida e o tratador de sinal não levanta uma exceção, a função agora tenta novamente a chamada de sistema em vez de levantar uma exceção
InterruptedError
(consulte PEP 475 para entender a lógica).
As seguintes constantes são opções para o parâmetro flags da função open()
. Elas podem ser combinadas usando o operador bitwise OR |
. Algumas delas não estão disponíveis em todas as plataformas. Para obter descrições de sua disponibilidade e uso, consulte a página do manual open(2) no Unix ou the MSDN no Windows.
-
os.
O_RDONLY
¶ -
os.
O_WRONLY
¶ -
os.
O_RDWR
¶ -
os.
O_APPEND
¶ -
os.
O_CREAT
¶ -
os.
O_EXCL
¶ -
os.
O_TRUNC
¶ As constantes acima estão disponíveis no Unix e Windows.
-
os.
O_DSYNC
¶ -
os.
O_RSYNC
¶ -
os.
O_SYNC
¶ -
os.
O_NDELAY
¶ -
os.
O_NONBLOCK
¶ -
os.
O_NOCTTY
¶ -
os.
O_CLOEXEC
¶ As constantes acima estão disponíveis apenas no Unix.
Alterado na versão 3.3: adiciona a constante
O_CLOEXEC
.
-
os.
O_BINARY
¶ -
os.
O_NOINHERIT
¶ -
os.
O_SHORT_LIVED
¶ -
os.
O_TEMPORARY
¶ -
os.
O_RANDOM
¶ -
os.
O_SEQUENTIAL
¶ -
os.
O_TEXT
¶ As constantes acima estão disponíveis apenas no Windows.
-
os.
O_ASYNC
¶ -
os.
O_DIRECT
¶ -
os.
O_DIRECTORY
¶ -
os.
O_NOFOLLOW
¶ -
os.
O_NOATIME
¶ -
os.
O_PATH
¶ -
os.
O_TMPFILE
¶ -
os.
O_SHLOCK
¶ -
os.
O_EXLOCK
¶ As constantes acima são extensões e não estarão presentes, se não forem definidos pela biblioteca C.
-
os.
openpty
()¶ Abrir um novo par de pseudo-terminal. Retorna um par de descritores de arquivos
(master, slave)
para o pty e o tty, respectivamente. Os novos descritores de arquivos são non-inheritable. Para uma abordagem (ligeiramente) mais portátil, use o módulopty
.Disponibilidade: alguns sabores de Unix
Alterado na versão 3.4: Os novos descritores de arquivos agora são não-herdáveis.
-
os.
pipe
()¶ Cria um encadeamento. Retorna um par de descritores de arquivos
(r, w)
usáveis para leitura e escrita, respectivamente. O novo descritor de arquivo é non-inheritable.Disponibilidade: Unix, Windows.
Alterado na versão 3.4: Os novos descritores de arquivos agora são não-herdáveis.
-
os.
pipe2
(flags)¶ Cria um canal com flags definidos atomicamente. flags podem ser construídos por ORing junto a um ou mais destes valores:
O_NONBLOCK
,O_CLOEXEC
. Retorna um par de descritores de arquivo(r, w)
utilizáveis para leitura e gravação, respectivamente.Disponibilidade: alguns sabores de Unix
Novo na versão 3.3.
-
os.
posix_fallocate
(fd, offset, len)¶ Garante que espaço em disco suficiente seja alocado para o arquivo especificado por fd iniciando em offset e continuando por len bytes.
Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
posix_fadvise
(fd, offset, len, advice)¶ Anuncia a intenção de acessar dados em um padrão específico, permitindo assim que o kernel faça otimizações. O aviso se aplica à região do arquivo especificado por fd, iniciando em offset e continuando por len bytes. advice é um entre
POSIX_FADV_NORMAL
,POSIX_FADV_SEQUENTIAL
,POSIX_FADV_RANDOM
,POSIX_FADV_NOREUSE
,POSIX_FADV_WILLNEED
ouPOSIX_FADV_DONTNEED
.Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
POSIX_FADV_NORMAL
¶ -
os.
POSIX_FADV_SEQUENTIAL
¶ -
os.
POSIX_FADV_RANDOM
¶ -
os.
POSIX_FADV_NOREUSE
¶ -
os.
POSIX_FADV_WILLNEED
¶ -
os.
POSIX_FADV_DONTNEED
¶ Sinalizadores que podem ser usados em advice em
posix_fadvise()
que especificam o padrão de acesso que provavelmente será usado.Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
pread
(fd, buffersize, offset)¶ Read from a file descriptor, fd, at a position of offset. It will read up to buffersize number of bytes. The file offset remains unchanged.
Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
pwrite
(fd, str, offset)¶ Write bytestring to a file descriptor, fd, from offset, leaving the file offset unchanged.
Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
read
(fd, n)¶ Read at most n bytes from file descriptor fd. Return a bytestring containing the bytes read. If the end of the file referred to by fd has been reached, an empty bytes object is returned.
Nota
Esta função destina-se a E/S de baixo nível e deve ser aplicada a um descritor de arquivo retornado por
os.open()
oupipe()
. Para ler um “objeto arquivo” retornado pela função embutidaopen()
ou porpopen()
oufdopen()
, ousys.stdin
, use seus métodosread()
oureadline()
.Alterado na versão 3.5: Se a chamada de sistema é interrompida e o tratador de sinal não levanta uma exceção, a função agora tenta novamente a chamada de sistema em vez de levantar uma exceção
InterruptedError
(consulte PEP 475 para entender a lógica).
-
os.
sendfile
(out, in, offset, count)¶ -
os.
sendfile
(out, in, offset, count, [headers, ][trailers, ]flags=0) Copy count bytes from file descriptor in to file descriptor out starting at offset. Return the number of bytes sent. When EOF is reached return 0.
A primeira notação de função é suportada por todas as plataformas que definem
sendfile()
.On Linux, if offset is given as
None
, the bytes are read from the current position of in and the position of in is updated.The second case may be used on Mac OS X and FreeBSD where headers and trailers are arbitrary sequences of buffers that are written before and after the data from in is written. It returns the same as the first case.
On Mac OS X and FreeBSD, a value of 0 for count specifies to send until the end of in is reached.
All platforms support sockets as out file descriptor, and some platforms allow other types (e.g. regular file, pipe) as well.
Os aplicativos de plataforma cruzada não devem usar os argumentos headers, trailers e flags.
Disponibilidade: Unix.
Nota
Para um wrapper de nível superior de
sendfile()
, consultesocket.socket.sendfile()
.Novo na versão 3.3.
-
os.
set_blocking
(fd, blocking)¶ Define o modo de bloqueio do descritor de arquivo especificado. Define o sinalizador
O_NONBLOCK
se bloqueio forFalse
; do contrário, limpa o sinalizador.Veja também
get_blocking()
esocket.socket.setblocking()
.Disponibilidade: Unix.
Novo na versão 3.5.
-
os.
SF_NODISKIO
¶ -
os.
SF_MNOWAIT
¶ -
os.
SF_SYNC
¶ Parâmetros para a função
sendfile()
, se a implementação tiver suporte a eles.Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
readv
(fd, buffers)¶ Read from a file descriptor fd into a number of mutable bytes-like objects buffers.
readv()
will transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data.readv()
returns the total number of bytes read (which may be less than the total capacity of all the objects).Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
tcgetpgrp
(fd)¶ Retorna o grupo de processos associado ao terminal fornecido por fd (um descritor de arquivo aberto conforme retornado por
os.open()
).Disponibilidade: Unix.
-
os.
tcsetpgrp
(fd, pg)¶ Define o grupo de processos associado ao terminal fornecido por fd (um descritor de arquivo aberto conforme retornado por
os.open()
) para pg.Disponibilidade: Unix.
-
os.
ttyname
(fd)¶ Retorna uma string que especifica o dispositivo de terminal associado ao descritor de arquivo fd. Se fd não estiver associado a um dispositivo de terminal, uma exceção é levantada.
Disponibilidade: Unix.
-
os.
write
(fd, str)¶ Write the bytestring in str to file descriptor fd. Return the number of bytes actually written.
Nota
Esta função destina-se a E/S de baixo nível e deve ser aplicada a um descritor de arquivo retornado por
os.open()
oupipe()
. Para escrever um “objeto arquivo” retornado pela função embutidaopen()
ou porpopen()
oufdopen()
, ousys.stdout
ousys.stderr
, use seu métodowrite()
.Alterado na versão 3.5: Se a chamada de sistema é interrompida e o tratador de sinal não levanta uma exceção, a função agora tenta novamente a chamada de sistema em vez de levantar uma exceção
InterruptedError
(consulte PEP 475 para entender a lógica).
-
os.
writev
(fd, buffers)¶ Write the contents of buffers to file descriptor fd. buffers must be a sequence of bytes-like objects. Buffers are processed in array order. Entire contents of first buffer is written before proceeding to second, and so on. The operating system may set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
writev()
writes the contents of each object to the file descriptor and returns the total number of bytes written.Disponibilidade: Unix.
Novo na versão 3.3.
16.1.4.1. Consultando o tamanho de um terminal¶
Novo na versão 3.3.
-
os.
get_terminal_size
(fd=STDOUT_FILENO)¶ Retorna o tamanho da janela do terminal como
(columns, lines)
, tupla do tipoterminal_size
.O argumento opcional
fd
(padrãoSTDOUT_FILENO
, ou saída padrão) especifica qual descritor de arquivo deve ser consultado.Se o descritor de arquivo não estiver conectado a um terminal, uma
OSError
é levantada.shutil.get_terminal_size()
é a função de alto nível que normalmente deve ser usada,os.get_terminal_size
é a implementação de baixo nível.Disponibilidade: Unix, Windows.
16.1.4.2. Herança de descritores de arquivo¶
Novo na versão 3.4.
Um descritor de arquivo tem um sinalizador “herdável” que indica se o descritor de arquivo pode ser herdado por processos filho. Desde o Python 3.4, os descritores de arquivo criados pelo Python não são herdáveis por padrão.
No UNIX, os descritores de arquivo não herdáveis são fechados em processos filho na execução de um novo programa, outros descritores de arquivo são herdados.
No Windows, identificadores não herdáveis e descritores de arquivo são fechados em processos filho, exceto para fluxos padrão (descritores de arquivo 0, 1 e 2: stdin, stdout e stderr), que são sempre herdados. Usando as funções spawn*
, todos os identificadores herdáveis e todos os descritores de arquivo herdáveis são herdados. Usando o módulo subprocess
, todos os descritores de arquivo, exceto fluxos padrão, são fechados, e os manipuladores herdáveis são herdados apenas se o parâmetro close_fds for False
.
-
os.
get_inheritable
(fd)¶ Obtém o sinalizador “herdável” do descritor de arquivo especificado (um booleano).
-
os.
set_inheritable
(fd, inheritable)¶ Define o sinalizador “herdável” do descritor de arquivo especificado.
-
os.
get_handle_inheritable
(handle)¶ Obtém o sinalizador “herdável” do manipulador especificado (um booleano).
Availability: Windows.
-
os.
set_handle_inheritable
(handle, inheritable)¶ Define o sinalizador “herdável” do manipulador especificado.
Availability: Windows.
16.1.5. Arquivos e Diretórios¶
Em algumas plataformas Unix, muitas dessas funções suportam um ou mais destes recursos:
specifying a file descriptor: For some functions, the path argument can be not only a string giving a path name, but also a file descriptor. The function will then operate on the file referred to by the descriptor. (For POSIX systems, Python will call the
f...
version of the function.)You can check whether or not path can be specified as a file descriptor on your platform using
os.supports_fd
. If it is unavailable, using it will raise aNotImplementedError
.If the function also supports dir_fd or follow_symlinks arguments, it is an error to specify one of those when supplying path as a file descriptor.
paths relative to directory descriptors: If dir_fd is not
None
, it should be a file descriptor referring to a directory, and the path to operate on should be relative; path will then be relative to that directory. If the path is absolute, dir_fd is ignored. (For POSIX systems, Python will call the...at
orf...at
version of the function.)You can check whether or not dir_fd is supported on your platform using
os.supports_dir_fd
. If it is unavailable, using it will raise aNotImplementedError
.
not following symlinks: If follow_symlinks is
False
, and the last element of the path to operate on is a symbolic link, the function will operate on the symbolic link itself instead of the file the link points to. (For POSIX systems, Python will call thel...
version of the function.)You can check whether or not follow_symlinks is supported on your platform using
os.supports_follow_symlinks
. If it is unavailable, using it will raise aNotImplementedError
.
-
os.
access
(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)¶ Usa o uid/gid real para testar o acesso ao path. Observe que a maioria das operações usará o uid/gid efetivo, portanto, essa rotina pode ser usada em um ambiente suid/sgid para testar se o usuário de chamada tem o acesso especificado ao path. mode deve ser
F_OK
para testar a existência de path, ou pode ser o OU inclusivo de um ou mais dosR_OK
,W_OK
, eX_OK
para testar as permissões. RetornaTrue
se o acesso for permitido,False
se não for. Veja a página man do Unix access(2) para mais informações.Esta função pode suportar a especificação de caminhos relativos aos descritores de diretório e não seguir os links simbólicos.
Se effective_ids for
True
,access()
irá realizar suas verificações de acesso usando o uid/gid efetivo ao invés do uid/gid real. effective_ids pode não ser compatível com sua plataforma; você pode verificar se está ou não disponível usando :data:ʻos.supports_effective_ids`. Se não estiver disponível, usá-lo levantará umaNotImplementedError
.Nota
Usar
access()
para verificar se um usuário está autorizado a, por exemplo, abrir um arquivo antes de realmente fazer isso usandoopen()
cria uma brecha de segurança, porque o usuário pode explorar o curto intervalo de tempo entre a verificação e a abertura do arquivo para manipulá-lo. É preferível usar as técnicas: term:EAFP. Por exemplo:if os.access("myfile", os.R_OK): with open("myfile") as fp: return fp.read() return "some default data"
É melhor escrito como:
try: fp = open("myfile") except PermissionError: return "some default data" else: with fp: return fp.read()
Nota
As operações de E/S podem falhar mesmo quando
access()
indica que elas teriam sucesso, particularmente para operações em sistemas de arquivos de rede que podem ter semântica de permissões além do modelo de bits de permissão POSIX usual.Alterado na versão 3.3: Adicionados os parâmetros dir_fd, effective_ids e follow_symlinks.
-
os.
F_OK
¶ -
os.
R_OK
¶ -
os.
W_OK
¶ -
os.
X_OK
¶ Valores a serem passados como o parâmetro mode de
access()
para testar a existência, legibilidade, capacidade de escrita e executabilidade de path, respectivamente.
-
os.
chdir
(path)¶ Altera o diretório de trabalho atual para path.
Esta função pode ter suporte a especificar um descritor de arquivo. O descritor deve fazer referência a um diretório aberto, não a um arquivo aberto.
Novo na versão 3.3: Adicionado suporte para especificar path como um descritor de arquivo em algumas plataformas.
-
os.
chflags
(path, flags, *, follow_symlinks=True)¶ Define os sinalizadores de path para os flags numéricos. flags podem assumir uma combinação (OU bit a bit) dos seguintes valores (conforme definido no módulo
stat
):stat.UF_NODUMP
stat.UF_IMMUTABLE
stat.UF_APPEND
stat.UF_OPAQUE
stat.UF_NOUNLINK
stat.UF_COMPRESSED
stat.UF_HIDDEN
stat.SF_ARCHIVED
stat.SF_IMMUTABLE
stat.SF_APPEND
stat.SF_NOUNLINK
stat.SF_SNAPSHOT
Esta função pode ter suporte a não seguir links simbólicos.
Disponibilidade: Unix.
Novo na versão 3.3: O argumento follow_symlinks.
-
os.
chmod
(path, mode, *, dir_fd=None, follow_symlinks=True)¶ Altera o modo de path para o mode numérico. mode pode assumir um dos seguintes valores (conforme definido no módulo
stat
) ou combinações de OU bit a bit deles:stat.S_ISUID
stat.S_ISGID
stat.S_ENFMT
stat.S_ISVTX
stat.S_IREAD
stat.S_IWRITE
stat.S_IEXEC
stat.S_IRWXU
stat.S_IRUSR
stat.S_IWUSR
stat.S_IXUSR
stat.S_IRWXG
stat.S_IRGRP
stat.S_IWGRP
stat.S_IXGRP
stat.S_IRWXO
stat.S_IROTH
stat.S_IWOTH
stat.S_IXOTH
Esta função pode ter suporte a especificar um descritor de arquivo, caminhos relativos aos descritores de diretório e não seguir os links simbólicos.
Nota
Embora o Windows tenha suporte ao
chmod()
, você só pode definir o sinalizador de somente leitura do arquivo com ele (através das constantesstat.S_IWRITE
estat.S_IREAD
ou um valor inteiro correspondente). Todos os outros bits são ignorados.Novo na versão 3.3: Adicionado suporte para especificar path como um descritor de arquivo aberto e os argumentos dir_fd e follow_symlinks.
-
os.
chown
(path, uid, gid, *, dir_fd=None, follow_symlinks=True)¶ Altera o proprietário e o id de grupo de path para uid e gid numéricos. Para deixar um dos ids inalterado, defina-o como -1.
Esta função pode ter suporte a especificar um descritor de arquivo, caminhos relativos aos descritores de diretório e não seguir os links simbólicos.
Consulte
shutil.chown()
para uma função de alto nível que aceita nomes além de ids numéricos.Disponibilidade: Unix.
Novo na versão 3.3: Added support for specifying an open file descriptor for path, and the dir_fd and follow_symlinks arguments.
-
os.
chroot
(path)¶ Altere o diretório raiz do processo atual para path
Disponibilidade: Unix.
-
os.
fchdir
(fd)¶ Altera o diretório de trabalho atual para o diretório representado pelo descritor de arquivo fd. O descritor deve se referir a um diretório aberto, não a um arquivo aberto. No Python 3.3, isso é equivalente a
os.chdir(fd)
.Disponibilidade: Unix.
-
os.
getcwd
()¶ Retorna uma string representando o diretório de trabalho atual.
-
os.
getcwdb
()¶ Retorna uma bytestring representando o diretório de trabalho atual.
-
os.
lchflags
(path, flags)¶ Define os sinalizadores de path para os flags numéricos, como
chflags()
, mas não segue links simbólicos. No Python 3.3, isso é equivalente aos.chflags(path, flags, follow_symlinks=False)
.Disponibilidade: Unix.
-
os.
lchmod
(path, mode)¶ Altera o modo de path para o mode numérico. Se o caminho for um link simbólico, isso afetará o link simbólico em vez do destino. Veja a documentação de
chmod()
para valores possíveis de mode. No Python 3.3, isso é equivalente aos.chmod(path, mode, follow_symlinks=False)
.Disponibilidade: Unix.
-
os.
lchown
(path, uid, gid)¶ Altera o proprietário e o id de grupo de path para uid e gid numéricos. Esta função não seguirá links simbólicos. No Python 3.3, isso é equivalente a
os.chown(path, uid, gid, follow_symlinks=False)
.Disponibilidade: Unix.
-
os.
link
(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)¶ Cria um link físico apontando para src chamado dst.
Esta função pode suportar a especificação de src_dir_fd e/ou dst_dir_fd para fornecer caminhos relativos a descritores de diretório e não seguir links simbólicos.
Disponibilidade: Unix, Windows.
Alterado na versão 3.2: Adicionado suporte ao Windows.
Novo na versão 3.3: Adiciona os argumentos src_dir_fd, dst_dir_fd e follow_symlinks.
-
os.
listdir
(path='.')¶ Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries
'.'
and'..'
even if they are present in the directory.path may be either of type
str
or of typebytes
. If path is of typebytes
, the filenames returned will also be of typebytes
; in all other circumstances, they will be of typestr
.Esta função também pode ter suporte a especificar um descritor de arquivo; o descritor de arquivo deve fazer referência a um diretório.
Nota
Para codificar nomes de arquivos
str
parabytes
, usefsencode()
.Ver também
A função
scandir()
retorna entradas de diretório junto com informações de atributo de arquivo, dando melhor desempenho para muitos casos de uso comuns.Alterado na versão 3.2: O parâmetro path tornou-se opcional.
Novo na versão 3.3: Added support for specifying an open file descriptor for path.
-
os.
lstat
(path, *, dir_fd=None)¶ Executa o equivalente a uma chamada de sistema
lstat()
no caminho fornecido. Semelhante astat()
, mas não segue links simbólicos. Retorna um objetostat_result
.Em plataformas que não têm suporte a links simbólicos, este é um alias para
stat()
.No Python 3.3, isso é equivalente a
os.stat(path, dir_fd=dir_fd, follow_symlinks=False)
.Esta função também pode ter suporte a caminhos relativos a descritores de diretório.
Ver também
A função
stat()
.Alterado na versão 3.2: Adicionado suporte para links simbólicos do Windows 6.0 (Vista).
Alterado na versão 3.3: Adicionado o parâmetro dir_fd.
-
os.
mkdir
(path, mode=0o777, *, dir_fd=None)¶ Cria um diretório chamado path com o modo numérico mode.
Se o diretório já existe,
FileExistsError
é levantada.Em alguns sistemas, mode é ignorado. Onde ele é usado, o valor atual do umask é primeiro mascarado. Se bits diferentes dos últimos 9 (ou seja, os últimos 3 dígitos da representação octal do mode) são definidos, seu significado depende da plataforma. Em algumas plataformas, eles são ignorados e você deve chamar
chmod()
explicitamente para defini-los.Esta função também pode ter suporte a caminhos relativos a descritores de diretório.
Também é possível criar diretórios temporários; veja a função
tempfile.mkdtemp()
do módulotempfile
.Novo na versão 3.3: O argumento dir_fd.
-
os.
makedirs
(name, mode=0o777, exist_ok=False)¶ Função de criação recursiva de diretório. Como
mkdir()
, mas torna todos os diretórios de nível intermediário necessários para conter o diretório folha.The mode parameter is passed to
mkdir()
; see the mkdir() description for how it is interpreted.If exist_ok is
False
(the default), anOSError
is raised if the target directory already exists.Nota
makedirs()
ficará confuso se os elementos do caminho a serem criados incluírempardir
(por exemplo, “..” em sistemas UNIX).Esta função trata os caminhos UNC corretamente.
Novo na versão 3.2: O parâmetro exist_ok.
Alterado na versão 3.4.1: Antes do Python 3.4.1, se exist_ok fosse
True
e o diretório existisse,makedirs()
ainda levantaria um erro se mode não correspondesse ao modo do diretório existente. Como esse comportamento era impossível de implementar com segurança, ele foi removido no Python 3.4.1. Consulte bpo-21082.
-
os.
mkfifo
(path, mode=0o666, *, dir_fd=None)¶ Cria um FIFO (um encadeamento nomeado) chamado path com o modo numérico mode. O valor atual de umask é primeiro mascarado do modo.
Esta função também pode ter suporte a caminhos relativos a descritores de diretório.
FIFOs são canais que podem ser acessados como arquivos regulares. FIFOs existem até que sejam excluídos (por exemplo, com
os.unlink()
). Geralmente, os FIFOs são usados como ponto de encontro entre os processos do tipo “cliente” e “servidor”: o servidor abre o FIFO para leitura e o cliente para escrita. Observe quemkfifo()
não abre o FIFO – apenas cria o ponto de encontro.Disponibilidade: Unix.
Novo na versão 3.3: O argumento dir_fd.
-
os.
mknod
(path, mode=0o600, device=0, *, dir_fd=None)¶ Cria um nó de sistema de arquivos (arquivo, arquivo especial de dispositivo ou canal nomeado) chamado path. mode especifica as permissões de uso e o tipo de nó a ser criado, sendo combinado (OU bit a bit) com um de
stat.S_IFREG
,stat.S_IFCHR
,stat.S_IFBLK
, estat.S_IFIFO
(essas constantes estão disponíveis emstat
). Parastat.S_IFCHR
estat.S_IFBLK
, device define o arquivo especial do dispositivo recém-criado (provavelmente usandoos.makedev()
), caso contrário, ele será ignorado.Esta função também pode ter suporte a caminhos relativos a descritores de diretório.
Disponibilidade: Unix.
Novo na versão 3.3: O argumento dir_fd.
-
os.
major
(device)¶ Extrai o número principal de dispositivo de um número bruto de dispositivo (normalmente o campo
st_dev
oust_rdev
destat
).
-
os.
minor
(device)¶ Extrai o número secundário de dispositivo de um número bruto de dispositivo (geralmente o campo
st_dev
oust_rdev
destat
).
-
os.
makedev
(major, minor)¶ Compõe um número de dispositivo bruto a partir dos números de dispositivo principais e secundários.
-
os.
pathconf
(path, name)¶ Retorna informações de configuração do sistema relevantes para um arquivo nomeado. name especifica o valor de configuração a ser recuperado; pode ser uma string que é o nome de um valor de sistema definido; esses nomes são especificados em vários padrões (POSIX.1, Unix 95, Unix 98 e outros). Algumas plataformas também definem nomes adicionais. Os nomes conhecidos do sistema operacional do host são fornecidos no dicionário
pathconf_names
. Para variáveis de configuração não incluídas nesse mapeamento, passar um número inteiro para name também é aceito.Se name for uma string e não for conhecida,
ValueError
é gerado. Se um valor específico para name não for compatível com o sistema de host, mesmo que seja incluído nopathconf_names
, um erroOSError
é gerado comerrno.EINVAL
como número do erro.Esta função tem suporte a especificar um descritor de arquivo.
Disponibilidade: Unix.
-
os.
pathconf_names
¶ Nomes de mapeamento de dicionário aceitos por
pathconf()
efpathconf()
para os valores inteiros definidos para esses nomes pelo sistema operacional do host. Isso pode ser usado para determinar o conjunto de nomes conhecidos pelo sistema.Disponibilidade: Unix.
-
os.
readlink
(path, *, dir_fd=None)¶ Retorna uma string representando o caminho para o qual o link simbólico aponta. O resultado pode ser um nome de caminho absoluto ou relativo; se for relativo, pode ser convertido para um caminho absoluto usando
os.path.join(os.path.dirname(path), result)
.If the path is a string object, the result will also be a string object, and the call may raise a UnicodeDecodeError. If the path is a bytes object, the result will be a bytes object.
Esta função também pode ter suporte a caminhos relativos a descritores de diretório.
Disponibilidade: Unix, Windows
Alterado na versão 3.2: Adicionado suporte para links simbólicos do Windows 6.0 (Vista).
Novo na versão 3.3: O argumento dir_fd.
-
os.
remove
(path, *, dir_fd=None)¶ Remove (delete) the file path. If path is a directory,
OSError
is raised. Usermdir()
to remove directories.Esta função pode suportar paths relative to directory descriptors.
No Windows, a tentativa de remover um arquivo que está em uso causa o surgimento de uma exceção; no Unix, a entrada do diretório é removida, mas o armazenamento alocado para o arquivo não é disponibilizado até que o arquivo original não esteja mais em uso.
Esta função é semanticamente idêntica a
unlink()
.Novo na versão 3.3: O argumento dir_fd.
-
os.
removedirs
(name)¶ Remove os diretórios recursivamente. Funciona como
rmdir()
, exceto que, se o diretório folha for removido com sucesso,removedirs()
tenta remover sucessivamente todos os diretórios pai mencionados em path até que um erro seja levantado (que é ignorado, porque geralmente significa que um diretório pai não está vazio). Por exemplo,os.removedirs('foo/bar/baz')
primeiro removerá o diretório'foo/bar/baz'
, e então removerá'foo/bar'
e'foo'
se estiverem vazios. LevantaOSError
se o diretório folha não pôde ser removido com sucesso.
-
os.
rename
(src, dst, *, src_dir_fd=None, dst_dir_fd=None)¶ Rename the file or directory src to dst. If dst is a directory,
OSError
will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists,OSError
will be raised even if it is a file.Esta função pode suportar a especificação de src_dir_fd e/ou dst_dir_fd para fornecer caminhos relativos a descritores de diretório.
Se você quiser sobrescrita multiplataforma do destino, use
replace()
.Novo na versão 3.3: Os argumentos src_dir_fd e dst_dir_fd.
-
os.
renames
(old, new)¶ Diretório recursivo ou função de renomeação de arquivo. Funciona como
rename()
, exceto que a criação de qualquer diretório intermediário necessário para tornar o novo nome de caminho bom é tentada primeiro. Após a renomeação, os diretórios correspondentes aos segmentos de caminho mais à direita do nome antigo serão removidos usandoremovedirs()
.Nota
Esta função pode falhar com a nova estrutura de diretório criada se você não tiver as permissões necessárias para remover o arquivo ou diretório folha.
-
os.
replace
(src, dst, *, src_dir_fd=None, dst_dir_fd=None)¶ Renomeia o arquivo ou diretório src para dst. Se dst for um diretório,
OSError
será levantada. Se dst existir e for um arquivo, ele será substituído silenciosamente se o usuário tiver permissão. A operação pode falhar se src e dst estiverem em sistemas de arquivos diferentes. Se for bem-sucedido, a renomeação será uma operação atômica (este é um requisito POSIX).Esta função pode suportar a especificação de src_dir_fd e/ou dst_dir_fd para fornecer caminhos relativos a descritores de diretório.
Novo na versão 3.3.
-
os.
rmdir
(path, *, dir_fd=None)¶ Remove (delete) the directory path. Only works when the directory is empty, otherwise,
OSError
is raised. In order to remove whole directory trees,shutil.rmtree()
can be used.Esta função pode suportar paths relative to directory descriptors.
Novo na versão 3.3: O parâmetro dir_fd.
-
os.
scandir
(path='.')¶ Return an iterator of
DirEntry
objects corresponding to the entries in the directory given by path. The entries are yielded in arbitrary order, and the special entries'.'
and'..'
are not included.Using
scandir()
instead oflistdir()
can significantly increase the performance of code that also needs file type or file attribute information, becauseDirEntry
objects expose this information if the operating system provides it when scanning a directory. AllDirEntry
methods may perform a system call, butis_dir()
andis_file()
usually only require a system call for symbolic links;DirEntry.stat()
always requires a system call on Unix but only requires one for symbolic links on Windows.On Unix, path can be of type
str
orbytes
(usefsencode()
andfsdecode()
to encode and decodebytes
paths). On Windows, path must be of typestr
. On both systems, the type of thename
andpath
attributes of eachDirEntry
will be of the same type as path.O exemplo a seguir mostra um uso simples de
scandir()
para exibir todos os arquivos (excluindo diretórios) no path fornecido que não começa com'.'
. A chamadaentry.is_file()
geralmente não fará uma chamada de sistema adicional:for entry in os.scandir(path): if not entry.name.startswith('.') and entry.is_file(): print(entry.name)
Nota
Em sistemas baseados no Unix,
scandir()
utilize o sistema opendir() e as funções readdir(). No Windows, será utilizado o Win32 FindFirstFileW e a função FindNextFileW.Novo na versão 3.5.
-
class
os.
DirEntry
¶ Objeto produzido por
scandir()
para expor o caminho do arquivo e outros atributos de arquivo de uma entrada de diretório.scandir()
will provide as much of this information as possible without making additional system calls. When astat()
orlstat()
system call is made, theDirEntry
object will cache the result.DirEntry
instances are not intended to be stored in long-lived data structures; if you know the file metadata has changed or if a long time has elapsed since callingscandir()
, callos.stat(entry.path)
to fetch up-to-date information.Because the
DirEntry
methods can make operating system calls, they may also raiseOSError
. If you need very fine-grained control over errors, you can catchOSError
when calling one of theDirEntry
methods and handle as appropriate.Attributes and methods on a
DirEntry
instance are as follows:-
name
¶ O nome do arquivo base da entrada, relativo ao argumento path de
scandir()
.The
name
attribute will be of the same type (str
orbytes
) as thescandir()
path argument. Usefsdecode()
to decode byte filenames.
-
path
¶ The entry’s full path name: equivalent to
os.path.join(scandir_path, entry.name)
where scandir_path is thescandir()
path argument. The path is only absolute if thescandir()
path argument was absolute.The
path
attribute will be of the same type (str
orbytes
) as thescandir()
path argument. Usefsdecode()
to decode byte filenames.
-
inode
()¶ Retorna o número de nó-i da entrada.
The result is cached on the
DirEntry
object. Useos.stat(entry.path, follow_symlinks=False).st_ino
to fetch up-to-date information.Na primeira chamada sem cache, uma chamada de sistema é necessária no Windows, mas não no Unix.
-
is_dir
(*, follow_symlinks=True)¶ Retorna
True
se esta entrada for um diretório ou um link simbólico apontando para um diretório; retornaFalse
se a entrada é ou aponta para qualquer outro tipo de arquivo, ou se ele não existe mais.Se follow_symlinks for
False
, retornaTrue
apenas se esta entrada for um diretório (sem seguir os links simbólicos); retornaFalse
se a entrada for qualquer outro tipo de arquivo ou se ele não existe mais.The result is cached on the
DirEntry
object, with a separate cache for follow_symlinksTrue
andFalse
. Callos.stat()
along withstat.S_ISDIR()
to fetch up-to-date information.Na primeira chamada sem cache, nenhuma chamada do sistema é necessária na maioria dos casos. Especificamente, para links não simbólicos, nem o Windows nem o Unix requerem uma chamada de sistema, exceto em certos sistemas de arquivos Unix, como sistemas de arquivos de rede, que retornam
dirent.d_type == DT_UNKNOWN
. Se a entrada for um link simbólico, uma chamada de sistema será necessária para seguir o link simbólico, a menos que follow_symlinks sejaFalse
.Este método pode levantar
OSError
, tal comoPermissionError
, masFileNotFoundError
é capturada e não levantada.
-
is_file
(*, follow_symlinks=True)¶ Retorna
True
se esta entrada for um arquivo ou um link simbólico apontando para um arquivo; retornaFalse
se a entrada é ou aponta para um diretório ou outra entrada que não seja de arquivo, ou se ela não existe mais.Se follow_symlinks for
False
, retornaTrue
apenas se esta entrada for um arquivo (sem seguir os links simbólicos); retornaFalse
se a entrada for um diretório ou outra entrada que não seja um arquivo, ou se ela não existir mais.The result is cached on the
DirEntry
object. Caching, system calls made, and exceptions raised are as peris_dir()
.
-
is_symlink
()¶ Retorna
True
se esta entrada for um link simbólico (mesmo se quebrado); retornaFalse
se a entrada apontar para um diretório ou qualquer tipo de arquivo, ou se ele não existir mais.The result is cached on the
DirEntry
object. Callos.path.islink()
to fetch up-to-date information.Na primeira chamada sem cache, nenhuma chamada do sistema é necessária na maioria dos casos. Especificamente, nem o Windows nem o Unix exigem uma chamada de sistema, exceto em certos sistemas de arquivos Unix, como sistemas de arquivos de rede, que retornam
dirent.d_type == DT_UNKNOWN
.Este método pode levantar
OSError
, tal comoPermissionError
, masFileNotFoundError
é capturada e não levantada.
-
stat
(*, follow_symlinks=True)¶ Retorna um objeto
stat_result
para esta entrada. Este método segue links simbólicos por padrão; para estabelecer um link simbólico, adicione o argumentofollow_symlinks=False
.On Unix, this method always requires a system call. On Windows, it only requires a system call if follow_symlinks is
True
and the entry is a symbolic link.No Windows, os atributos
st_ino
,st_dev
est_nlink
dastat_result
são sempre definidos como zero. Chameos.stat()
para obter esses atributos.The result is cached on the
DirEntry
object, with a separate cache for follow_symlinksTrue
andFalse
. Callos.stat()
to fetch up-to-date information.
Note that there is a nice correspondence between several attributes and methods of
DirEntry
and ofpathlib.Path
. In particular, thename
attribute has the same meaning, as do theis_dir()
,is_file()
,is_symlink()
andstat()
methods.Novo na versão 3.5.
-
-
os.
stat
(path, *, dir_fd=None, follow_symlinks=True)¶ Get the status of a file or a file descriptor. Perform the equivalent of a
stat()
system call on the given path. path may be specified as either a string, a bytes or as an open file descriptor. Return astat_result
object.Esta função normalmente segue links simbólicos; para efetuar stat em um link simbólico, adicione o argumento
follow_symlinks=False
, ou uselstat()
.Esta função tem suporte a especificar um descritor de arquivo e não seguir links simbólicos.
Exemplo:
>>> import os >>> statinfo = os.stat('somefile.txt') >>> statinfo os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026, st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295, st_mtime=1297230027, st_ctime=1297230027) >>> statinfo.st_size 264
Novo na versão 3.3: Adicionados os argumentos dir_fd e follow_symlinks, especificando um descritor de arquivo em vez de um caminho.
-
class
os.
stat_result
¶ Objeto cujos atributos correspondem aproximadamente aos membros da estrutura
stat
. É usado para o resultado deos.stat()
,os.fstat()
eos.lstat()
.Atributos:
-
st_mode
¶ Modo de arquivo: tipo de arquivo e bits de modo de arquivo (permissões).
-
st_ino
¶ Inode number.
-
st_dev
¶ Identificador do dispositivo no qual este arquivo reside.
-
st_nlink
¶ Número de links físicos.
-
st_uid
¶ Identificador de usuário do proprietário do arquivo.
-
st_gid
¶ Identificador de grupo do proprietário do arquivo.
-
st_size
¶ Tamanho do arquivo em bytes, se for um arquivo normal ou um link simbólico. O tamanho de um link simbólico é o comprimento do nome do caminho que ele contém, sem um byte nulo final.
Timestamps:
-
st_atime
¶ Tempo do acesso mais recente expresso em segundos.
-
st_mtime
¶ Tempo da modificação de conteúdo mais recente expresso em segundos.
-
st_ctime
¶ Dependente da plataforma:
- a hora da mudança de metadados mais recente no Unix,
- a hora de criação no Windows, expresso em segundos.
-
st_atime_ns
¶ Hora do acesso mais recente expresso em nanossegundos como um número inteiro.
-
st_mtime_ns
¶ Hora da modificação de conteúdo mais recente expressa em nanossegundos como um número inteiro.
-
st_ctime_ns
¶ Dependente da plataforma:
- a hora da mudança de metadados mais recente no Unix,
- a hora de criação no Windows, expresso em nanossegundos como um número inteiro.
See also the
stat_float_times()
function.Nota
O significado e resolução exatos dos atributos
st_atime
,st_mtime
, andst_ctime
dependem do sistema operacional e do sistema de arquivos. Por exemplo, em sistemas Windows que usam os sistemas de arquivos FAT ou FAT32,st_mtime
tem resolução de 2 segundos, est_atime
tem resolução de apenas 1 dia. Consulte a documentação do sistema operacional para obter detalhes.Da mesma forma, embora
st_atime_ns
,st_mtime_ns
est_ctime_ns
sejam sempre expressos em nanossegundos, muitos sistemas não fornecem precisão de nanossegundos. Em sistemas que fornecem precisão de nanossegundos, o objeto de ponto flutuante usado para armazenarst_atime
,st_mtime
est_ctime
não pode preservar tudo, e como tal será ligeiramente inexato . Se você precisa dos carimbos de data/hora exatos, sempre deve usarst_atime_ns
,st_mtime_ns
est_ctime_ns
.Em alguns sistemas Unix (como Linux), os seguintes atributos também podem estar disponíveis:
-
st_blocks
¶ Número de blocos de 512 bytes alocados para o arquivo. Isso pode ser menor que
st_size
/512 quando o arquivo possuir lacunas.
-
st_blksize
¶ Tamanho de bloco “preferido” para E/S eficiente do sistema de arquivos. Gravar em um arquivo em partes menores pode causar uma leitura-modificação-reescrita ineficiente.
-
st_rdev
¶ Tipo de dispositivo, se for um dispositivo nó-i.
-
st_flags
¶ Sinalizadores definidos pelo usuário para arquivo.
Em outros sistemas Unix (como o FreeBSD), os seguintes atributos podem estar disponíveis (mas só podem ser preenchidos se o root tentar usá-los):
-
st_gen
¶ Número de geração do arquivo.
-
st_birthtime
¶ Horário da criação do arquivo.
Em sistemas Mac OS, os seguintes atributos também podem estar disponíveis:
-
st_rsize
¶ Tamanho real do arquivo.
-
st_creator
¶ Criador do arquivo.
-
st_type
¶ Tipo de arquivo.
On Windows systems, the following attribute is also available:
-
st_file_attributes
¶ Atributos de arquivos no Windows: membro
dwFileAttributes
da estruturaBY_HANDLE_FILE_INFORMATION
retornada porGetFileInformationByHandle()
. Veja as constantesFILE_ATTRIBUTE_*
no módulostat
.
O módulo padrão
stat
define funções e constantes que são úteis para extrair informações de uma estruturastat
. (No Windows, alguns itens são preenchidos com valores fictícios.)Para compatibilidade com versões anteriores, uma instância de
stat_result
também é acessível como uma tupla de pelo menos 10 inteiros, fornecendo os membros mais importantes (e portáveis) da estruturastat
, na ordemst_mode
,st_ino
,st_dev
,st_nlink
,st_uid
,st_gid
,st_size
,st_atime
,st_mtime
,st_ctime
. Mais itens podem ser adicionados no final por algumas implementações. Para compatibilidade com versões mais antigas do Python, acessarstat_result
como uma tupla sempre retorna inteiros.Novo na versão 3.3: Adicionados os membros
st_atime_ns
,st_mtime_ns
est_ctime_ns
.Novo na versão 3.5: Adicionado o membro
st_file_attributes
no Windows.-
-
os.
stat_float_times
([newvalue])¶ Determine whether
stat_result
represents time stamps as float objects. If newvalue isTrue
, future calls tostat()
return floats, if it isFalse
, future calls return ints. If newvalue is omitted, return the current setting.For compatibility with older Python versions, accessing
stat_result
as a tuple always returns integers.Python now returns float values by default. Applications which do not work correctly with floating point time stamps can use this function to restore the old behaviour.
The resolution of the timestamps (that is the smallest possible fraction) depends on the system. Some systems only support second resolution; on these systems, the fraction will always be zero.
It is recommended that this setting is only changed at program startup time in the __main__ module; libraries should never change this setting. If an application uses a library that works incorrectly if floating point time stamps are processed, this application should turn the feature off until the library has been corrected.
Obsoleto desde a versão 3.3.
-
os.
statvfs
(path)¶ Perform a
statvfs()
system call on the given path. The return value is an object whose attributes describe the filesystem on the given path, and correspond to the members of thestatvfs
structure, namely:f_bsize
,f_frsize
,f_blocks
,f_bfree
,f_bavail
,f_files
,f_ffree
,f_favail
,f_flag
,f_namemax
.Duas constantes de nível de módulo são definidas para os sinalizadores de bit do atributo
f_flag
: seST_RDONLY
for definido, o sistema de arquivos é montado somente leitura, e seST_NOSUID
estiver definido, a semântica dos bits setuid/setgid é desabilitada ou não é suportada.Constantes de nível de módulo adicionais são definidas para sistemas baseados em GNU/glibc. São elas
ST_NODEV
(impede o acesso aos arquivos especiais do dispositivo),ST_NOEXEC
(não permite a execução do programa),ST_SYNCHRONOUS
(as escritas são sincronizadas de uma vez),ST_MANDLOCK
(permitir bloqueios obrigatórios em um sistema de arquivos),ST_WRITE
(escrever no arquivo/diretório/symlink),ST_APPEND
(arquivo somente anexado),ST_IMMUTABLE
(arquivo imutável),ST_NOATIME
(não atualiza os tempos de acesso),ST_NODIRATIME
(não atualiza os tempos de acesso ao diretório),ST_RELATIME
(atualiza o atime relativo ao mtime/ctime).Esta função tem suporte a especificar um descritor de arquivo.
Alterado na versão 3.2: As constantes
ST_RDONLY
eST_NOSUID
foram adicionadas.Alterado na versão 3.4: As constantes
ST_NODEV
,ST_NOEXEC
,ST_SYNCHRONOUS
,ST_MANDLOCK
,ST_WRITE
,ST_APPEND
,ST_IMMUTABLE
,ST_NOATIME
,ST_NODIRATIME
eST_RELATIME
foram adicionadas.Disponibilidade: Unix.
Novo na versão 3.3: Added support for specifying an open file descriptor for path.
-
os.
supports_dir_fd
¶ A
Set
object indicating which functions in theos
module permit use of their dir_fd parameter. Different platforms provide different functionality, and an option that might work on one might be unsupported on another. For consistency’s sakes, functions that support dir_fd always allow specifying the parameter, but will raise an exception if the functionality is not actually available.To check whether a particular function permits use of its dir_fd parameter, use the
in
operator onsupports_dir_fd
. As an example, this expression determines whether the dir_fd parameter ofos.stat()
is locally available:os.stat in os.supports_dir_fd
Atualmente os parâmetros dir_fd funcionam apenas em plataformas Unix; nenhum deles funciona no Windows.
Novo na versão 3.3.
-
os.
supports_effective_ids
¶ A
Set
object indicating which functions in theos
module permit use of the effective_ids parameter foros.access()
. If the local platform supports it, the collection will containos.access()
, otherwise it will be empty.To check whether you can use the effective_ids parameter for
os.access()
, use thein
operator onsupports_effective_ids
, like so:os.access in os.supports_effective_ids
Currently effective_ids only works on Unix platforms; it does not work on Windows.
Novo na versão 3.3.
-
os.
supports_fd
¶ A
Set
object indicating which functions in theos
module permit specifying their path parameter as an open file descriptor. Different platforms provide different functionality, and an option that might work on one might be unsupported on another. For consistency’s sakes, functions that support fd always allow specifying the parameter, but will raise an exception if the functionality is not actually available.To check whether a particular function permits specifying an open file descriptor for its path parameter, use the
in
operator onsupports_fd
. As an example, this expression determines whetheros.chdir()
accepts open file descriptors when called on your local platform:os.chdir in os.supports_fd
Novo na versão 3.3.
-
os.
supports_follow_symlinks
¶ A
Set
object indicating which functions in theos
module permit use of their follow_symlinks parameter. Different platforms provide different functionality, and an option that might work on one might be unsupported on another. For consistency’s sakes, functions that support follow_symlinks always allow specifying the parameter, but will raise an exception if the functionality is not actually available.To check whether a particular function permits use of its follow_symlinks parameter, use the
in
operator onsupports_follow_symlinks
. As an example, this expression determines whether the follow_symlinks parameter ofos.stat()
is locally available:os.stat in os.supports_follow_symlinks
Novo na versão 3.3.
-
os.
symlink
(src, dst, target_is_directory=False, *, dir_fd=None)¶ Create a symbolic link pointing to src named dst.
On Windows, a symlink represents either a file or a directory, and does not morph to the target dynamically. If the target is present, the type of the symlink will be created to match. Otherwise, the symlink will be created as a directory if target_is_directory is
True
or a file symlink (the default) otherwise. On non-Window platforms, target_is_directory is ignored.Symbolic link support was introduced in Windows 6.0 (Vista).
symlink()
will raise aNotImplementedError
on Windows versions earlier than 6.0.Esta função pode suportar paths relative to directory descriptors.
Nota
On Windows, the SeCreateSymbolicLinkPrivilege is required in order to successfully create symlinks. This privilege is not typically granted to regular users but is available to accounts which can escalate privileges to the administrator level. Either obtaining the privilege or running your application as an administrator are ways to successfully create symlinks.
OSError
is raised when the function is called by an unprivileged user.Disponibilidade: Unix, Windows.
Alterado na versão 3.2: Adicionado suporte para links simbólicos do Windows 6.0 (Vista).
Novo na versão 3.3: Added the dir_fd argument, and now allow target_is_directory on non-Windows platforms.
-
os.
sync
()¶ Force write of everything to disk.
Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
truncate
(path, length)¶ Truncate the file corresponding to path, so that it is at most length bytes in size.
Esta função tem suporte a especificar um descritor de arquivo.
Disponibilidade: Unix, Windows.
Novo na versão 3.3.
Alterado na versão 3.5: Adicionado suporte para o Windows.
-
os.
unlink
(path, *, dir_fd=None)¶ Remove (delete) the file path. This function is semantically identical to
remove()
; theunlink
name is its traditional Unix name. Please see the documentation forremove()
for further information.Novo na versão 3.3: O parâmetro dir_fd.
-
os.
utime
(path, times=None, *, [ns, ]dir_fd=None, follow_symlinks=True)¶ Set the access and modified times of the file specified by path.
utime()
takes two optional parameters, times and ns. These specify the times set on path and are used as follows:- If ns is specified,
it must be a 2-tuple of the form
(atime_ns, mtime_ns)
where each member is an int expressing nanoseconds. - If times is not
None
, it must be a 2-tuple of the form(atime, mtime)
where each member is an int or float expressing seconds. - If times is
None
and ns is unspecified, this is equivalent to specifyingns=(atime_ns, mtime_ns)
where both times are the current time.
It is an error to specify tuples for both times and ns.
Whether a directory can be given for path depends on whether the operating system implements directories as files (for example, Windows does not). Note that the exact times you set here may not be returned by a subsequent
stat()
call, depending on the resolution with which your operating system records access and modification times; seestat()
. The best way to preserve exact times is to use the st_atime_ns and st_mtime_ns fields from theos.stat()
result object with the ns parameter to utime.Esta função pode ter suporte a especificar um descritor de arquivo, caminhos relativos aos descritores de diretório e não seguir os links simbólicos.
Novo na versão 3.3: Added support for specifying an open file descriptor for path, and the dir_fd, follow_symlinks, and ns parameters.
- If ns is specified,
it must be a 2-tuple of the form
-
os.
walk
(top, topdown=True, onerror=None, followlinks=False)¶ Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple
(dirpath, dirnames, filenames)
.dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding
'.'
and'..'
). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, doos.path.join(dirpath, name)
.If optional argument topdown is
True
or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown isFalse
, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.When topdown is
True
, the caller can modify the dirnames list in-place (perhaps usingdel
or slice assignment), andwalk()
will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to informwalk()
about directories the caller creates or renames before it resumeswalk()
again. Modifying dirnames when topdown isFalse
has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.By default, errors from the
listdir()
call are ignored. If optional argument onerror is specified, it should be a function; it will be called with one argument, anOSError
instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as thefilename
attribute of the exception object.By default,
walk()
will not walk down into symbolic links that resolve to directories. Set followlinks toTrue
to visit directories pointed to by symlinks, on systems that support them.Nota
Be aware that setting followlinks to
True
can lead to infinite recursion if a link points to a parent directory of itself.walk()
does not keep track of the directories it visited already.Nota
If you pass a relative pathname, don’t change the current working directory between resumptions of
walk()
.walk()
never changes the current directory, and assumes that its caller doesn’t either.This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory:
import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print(root, "consumes", end=" ") print(sum(getsize(join(root, name)) for name in files), end=" ") print("bytes in", len(files), "non-directory files") if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories
In the next example (simple implementation of
shutil.rmtree()
), walking the tree bottom-up is essential,rmdir()
doesn’t allow deleting a directory before the directory is empty:# Delete everything reachable from the directory named in "top", # assuming there are no symbolic links. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. import os for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name))
Alterado na versão 3.5: This function now calls
os.scandir()
instead ofos.listdir()
, making it faster by reducing the number of calls toos.stat()
.
-
os.
fwalk
(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)¶ This behaves exactly like
walk()
, except that it yields a 4-tuple(dirpath, dirnames, filenames, dirfd)
, and it supportsdir_fd
.dirpath, dirnames and filenames are identical to
walk()
output, and dirfd is a file descriptor referring to the directory dirpath.This function always supports paths relative to directory descriptors and not following symlinks. Note however that, unlike other functions, the
fwalk()
default value for follow_symlinks isFalse
.Nota
Since
fwalk()
yields file descriptors, those are only valid until the next iteration step, so you should duplicate them (e.g. withdup()
) if you want to keep them longer.This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory:
import os for root, dirs, files, rootfd in os.fwalk('python/Lib/email'): print(root, "consumes", end="") print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]), end="") print("bytes in", len(files), "non-directory files") if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories
In the next example, walking the tree bottom-up is essential:
rmdir()
doesn’t allow deleting a directory before the directory is empty:# Delete everything reachable from the directory named in "top", # assuming there are no symbolic links. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. import os for root, dirs, files, rootfd in os.fwalk(top, topdown=False): for name in files: os.unlink(name, dir_fd=rootfd) for name in dirs: os.rmdir(name, dir_fd=rootfd)
Disponibilidade: Unix.
Novo na versão 3.3.
16.1.5.1. Atributos estendidos do Linux¶
Novo na versão 3.3.
These functions are all available on Linux only.
-
os.
getxattr
(path, attribute, *, follow_symlinks=True)¶ Return the value of the extended filesystem attribute attribute for path. attribute can be bytes or str. If it is str, it is encoded with the filesystem encoding.
Esta função tem suporte a especificar um descritor de arquivo e não seguir links simbólicos.
-
os.
listxattr
(path=None, *, follow_symlinks=True)¶ Return a list of the extended filesystem attributes on path. The attributes in the list are represented as strings decoded with the filesystem encoding. If path is
None
,listxattr()
will examine the current directory.Esta função tem suporte a especificar um descritor de arquivo e não seguir links simbólicos.
-
os.
removexattr
(path, attribute, *, follow_symlinks=True)¶ Removes the extended filesystem attribute attribute from path. attribute should be bytes or str. If it is a string, it is encoded with the filesystem encoding.
Esta função tem suporte a especificar um descritor de arquivo e não seguir links simbólicos.
-
os.
setxattr
(path, attribute, value, flags=0, *, follow_symlinks=True)¶ Set the extended filesystem attribute attribute on path to value. attribute must be a bytes or str with no embedded NULs. If it is a str, it is encoded with the filesystem encoding. flags may be
XATTR_REPLACE
orXATTR_CREATE
. IfXATTR_REPLACE
is given and the attribute does not exist,EEXISTS
will be raised. IfXATTR_CREATE
is given and the attribute already exists, the attribute will not be created andENODATA
will be raised.Esta função tem suporte a especificar um descritor de arquivo e não seguir links simbólicos.
Nota
A bug in Linux kernel versions less than 2.6.39 caused the flags argument to be ignored on some filesystems.
-
os.
XATTR_SIZE_MAX
¶ The maximum size the value of an extended attribute can be. Currently, this is 64 KiB on Linux.
-
os.
XATTR_CREATE
¶ This is a possible value for the flags argument in
setxattr()
. It indicates the operation must create an attribute.
-
os.
XATTR_REPLACE
¶ This is a possible value for the flags argument in
setxattr()
. It indicates the operation must replace an existing attribute.
16.1.6. Process Management¶
These functions may be used to create and manage processes.
The various exec*
functions take a list of arguments for the new
program loaded into the process. In each case, the first of these arguments is
passed to the new program as its own name rather than as an argument a user may
have typed on a command line. For the C programmer, this is the argv[0]
passed to a program’s main()
. For example, os.execv('/bin/echo',
['foo', 'bar'])
will only print bar
on standard output; foo
will seem
to be ignored.
-
os.
abort
()¶ Generate a
SIGABRT
signal to the current process. On Unix, the default behavior is to produce a core dump; on Windows, the process immediately returns an exit code of3
. Be aware that calling this function will not call the Python signal handler registered forSIGABRT
withsignal.signal()
.
-
os.
execl
(path, arg0, arg1, ...)¶ -
os.
execle
(path, arg0, arg1, ..., env)¶ -
os.
execlp
(file, arg0, arg1, ...)¶ -
os.
execlpe
(file, arg0, arg1, ..., env)¶ -
os.
execv
(path, args)¶ -
os.
execve
(path, args, env)¶ -
os.
execvp
(file, args)¶ -
os.
execvpe
(file, args, env)¶ These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as
OSError
exceptions.The current process is replaced immediately. Open file objects and descriptors are not flushed, so if there may be data buffered on these open files, you should flush them using
sys.stdout.flush()
oros.fsync()
before calling anexec*
function.The “l” and “v” variants of the
exec*
functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to theexecl*()
functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process should start with the name of the command being run, but this is not enforced.The variants which include a “p” near the end (
execlp()
,execlpe()
,execvp()
, andexecvpe()
) will use thePATH
environment variable to locate the program file. When the environment is being replaced (using one of theexec*e
variants, discussed in the next paragraph), the new environment is used as the source of thePATH
variable. The other variants,execl()
,execle()
,execv()
, andexecve()
, will not use thePATH
variable to locate the executable; path must contain an appropriate absolute or relative path.For
execle()
,execlpe()
,execve()
, andexecvpe()
(note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (these are used instead of the current process’ environment); the functionsexecl()
,execlp()
,execv()
, andexecvp()
all cause the new process to inherit the environment of the current process.For
execve()
on some platforms, path may also be specified as an open file descriptor. This functionality may not be supported on your platform; you can check whether or not it is available usingos.supports_fd
. If it is unavailable, using it will raise aNotImplementedError
.Disponibilidade: Unix, Windows.
Novo na versão 3.3: Added support for specifying an open file descriptor for path for
execve()
.
-
os.
_exit
(n)¶ Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc.
The following exit codes are defined and can be used with _exit()
,
although they are not required. These are typically used for system programs
written in Python, such as a mail server’s external command delivery program.
Nota
Some of these may not be available on all Unix platforms, since there is some variation. These constants are defined where they are defined by the underlying platform.
-
os.
EX_OK
¶ Exit code that means no error occurred.
Disponibilidade: Unix.
-
os.
EX_USAGE
¶ Exit code that means the command was used incorrectly, such as when the wrong number of arguments are given.
Disponibilidade: Unix.
-
os.
EX_DATAERR
¶ Exit code that means the input data was incorrect.
Disponibilidade: Unix.
-
os.
EX_NOINPUT
¶ Exit code that means an input file did not exist or was not readable.
Disponibilidade: Unix.
-
os.
EX_NOUSER
¶ Exit code that means a specified user did not exist.
Disponibilidade: Unix.
-
os.
EX_NOHOST
¶ Exit code that means a specified host did not exist.
Disponibilidade: Unix.
-
os.
EX_UNAVAILABLE
¶ Exit code that means that a required service is unavailable.
Disponibilidade: Unix.
-
os.
EX_SOFTWARE
¶ Exit code that means an internal software error was detected.
Disponibilidade: Unix.
-
os.
EX_OSERR
¶ Exit code that means an operating system error was detected, such as the inability to fork or create a pipe.
Disponibilidade: Unix.
-
os.
EX_OSFILE
¶ Exit code that means some system file did not exist, could not be opened, or had some other kind of error.
Disponibilidade: Unix.
-
os.
EX_CANTCREAT
¶ Exit code that means a user specified output file could not be created.
Disponibilidade: Unix.
-
os.
EX_IOERR
¶ Exit code that means that an error occurred while doing I/O on some file.
Disponibilidade: Unix.
-
os.
EX_TEMPFAIL
¶ Exit code that means a temporary failure occurred. This indicates something that may not really be an error, such as a network connection that couldn’t be made during a retryable operation.
Disponibilidade: Unix.
-
os.
EX_PROTOCOL
¶ Exit code that means that a protocol exchange was illegal, invalid, or not understood.
Disponibilidade: Unix.
-
os.
EX_NOPERM
¶ Exit code that means that there were insufficient permissions to perform the operation (but not intended for file system problems).
Disponibilidade: Unix.
-
os.
EX_CONFIG
¶ Exit code that means that some kind of configuration error occurred.
Disponibilidade: Unix.
-
os.
EX_NOTFOUND
¶ Exit code that means something like “an entry was not found”.
Disponibilidade: Unix.
-
os.
fork
()¶ Fork a child process. Return
0
in the child and the child’s process id in the parent. If an error occursOSError
is raised.Note that some platforms including FreeBSD <= 6.3 and Cygwin have known issues when using fork() from a thread.
Aviso
See
ssl
for applications that use the SSL module with fork().Disponibilidade: Unix.
-
os.
forkpty
()¶ Fork a child process, using a new pseudo-terminal as the child’s controlling terminal. Return a pair of
(pid, fd)
, where pid is0
in the child, the new child’s process id in the parent, and fd is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use thepty
module. If an error occursOSError
is raised.Disponibilidade: alguns sabores de Unix
-
os.
kill
(pid, sig)¶ Send signal sig to the process pid. Constants for the specific signals available on the host platform are defined in the
signal
module.Windows: The
signal.CTRL_C_EVENT
andsignal.CTRL_BREAK_EVENT
signals are special signals which can only be sent to console processes which share a common console window, e.g., some subprocesses. Any other value for sig will cause the process to be unconditionally killed by the TerminateProcess API, and the exit code will be set to sig. The Windows version ofkill()
additionally takes process handles to be killed.See also
signal.pthread_kill()
.Novo na versão 3.2: Windows support.
-
os.
killpg
(pgid, sig)¶ Envia o sinal sig para o grupo de processo pgid.
Disponibilidade: Unix.
-
os.
nice
(increment)¶ Add increment to the process’s “niceness”. Return the new niceness.
Disponibilidade: Unix.
-
os.
plock
(op)¶ Lock program segments into memory. The value of op (defined in
<sys/lock.h>
) determines which segments are locked.Disponibilidade: Unix.
-
os.
popen
(cmd, mode='r', buffering=-1)¶ Open a pipe to or from command cmd. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is
'r'
(default) or'w'
. The buffering argument has the same meaning as the corresponding argument to the built-inopen()
function. The returned file object reads or writes text strings rather than bytes.The
close
method returnsNone
if the subprocess exited successfully, or the subprocess’s return code if there was an error. On POSIX systems, if the return code is positive it represents the return value of the process left-shifted by one byte. If the return code is negative, the process was terminated by the signal given by the negated value of the return code. (For example, the return value might be- signal.SIGKILL
if the subprocess was killed.) On Windows systems, the return value contains the signed integer return code from the child process.This is implemented using
subprocess.Popen
; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.
-
os.
spawnl
(mode, path, ...)¶ -
os.
spawnle
(mode, path, ..., env)¶ -
os.
spawnlp
(mode, file, ...)¶ -
os.
spawnlpe
(mode, file, ..., env)¶ -
os.
spawnv
(mode, path, args)¶ -
os.
spawnve
(mode, path, args, env)¶ -
os.
spawnvp
(mode, file, args)¶ -
os.
spawnvpe
(mode, file, args, env)¶ Execute the program path in a new process.
(Note that the
subprocess
module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions. Check especially the Replacing Older Functions with the subprocess Module section.)If mode is
P_NOWAIT
, this function returns the process id of the new process; if mode isP_WAIT
, returns the process’s exit code if it exits normally, or-signal
, where signal is the signal that killed the process. On Windows, the process id will actually be the process handle, so can be used with thewaitpid()
function.The “l” and “v” variants of the
spawn*
functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to thespawnl*()
functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process must start with the name of the command being run.The variants which include a second “p” near the end (
spawnlp()
,spawnlpe()
,spawnvp()
, andspawnvpe()
) will use thePATH
environment variable to locate the program file. When the environment is being replaced (using one of thespawn*e
variants, discussed in the next paragraph), the new environment is used as the source of thePATH
variable. The other variants,spawnl()
,spawnle()
,spawnv()
, andspawnve()
, will not use thePATH
variable to locate the executable; path must contain an appropriate absolute or relative path.For
spawnle()
,spawnlpe()
,spawnve()
, andspawnvpe()
(note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (they are used instead of the current process’ environment); the functionsspawnl()
,spawnlp()
,spawnv()
, andspawnvp()
all cause the new process to inherit the environment of the current process. Note that keys and values in the env dictionary must be strings; invalid keys or values will cause the function to fail, with a return value of127
.As an example, the following calls to
spawnlp()
andspawnvpe()
are equivalent:import os os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') L = ['cp', 'index.html', '/dev/null'] os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
Availability: Unix, Windows.
spawnlp()
,spawnlpe()
,spawnvp()
andspawnvpe()
are not available on Windows.spawnle()
andspawnve()
are not thread-safe on Windows; we advise you to use thesubprocess
module instead.
-
os.
P_NOWAIT
¶ -
os.
P_NOWAITO
¶ Possible values for the mode parameter to the
spawn*
family of functions. If either of these values is given, thespawn*()
functions will return as soon as the new process has been created, with the process id as the return value.Disponibilidade: Unix, Windows.
-
os.
P_WAIT
¶ Possible value for the mode parameter to the
spawn*
family of functions. If this is given as mode, thespawn*()
functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or-signal
if a signal kills the process.Disponibilidade: Unix, Windows.
-
os.
P_DETACH
¶ -
os.
P_OVERLAY
¶ Possible values for the mode parameter to the
spawn*
family of functions. These are less portable than those listed above.P_DETACH
is similar toP_NOWAIT
, but the new process is detached from the console of the calling process. IfP_OVERLAY
is used, the current process will be replaced; thespawn*
function will not return.Availability: Windows.
-
os.
startfile
(path[, operation])¶ Start a file with its associated application.
When operation is not specified or
'open'
, this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.When another operation is given, it must be a “command verb” that specifies what should be done with the file. Common verbs documented by Microsoft are
'print'
and'edit'
(to be used on files) as well as'explore'
and'find'
(to be used on directories).startfile()
returns as soon as the associated application is launched. There is no option to wait for the application to close, and no way to retrieve the application’s exit status. The path parameter is relative to the current directory. If you want to use an absolute path, make sure the first character is not a slash ('/'
); the underlying Win32ShellExecute()
function doesn’t work if it is. Use theos.path.normpath()
function to ensure that the path is properly encoded for Win32.To reduce interpreter startup overhead, the Win32
ShellExecute()
function is not resolved until this function is first called. If the function cannot be resolved,NotImplementedError
will be raised.Availability: Windows.
-
os.
system
(command)¶ Execute the command (a string) in a subshell. This is implemented by calling the Standard C function
system()
, and has the same limitations. Changes tosys.stdin
, etc. are not reflected in the environment of the executed command. If command generates any output, it will be sent to the interpreter standard output stream.On Unix, the return value is the exit status of the process encoded in the format specified for
wait()
. Note that POSIX does not specify the meaning of the return value of the Csystem()
function, so the return value of the Python function is system-dependent.On Windows, the return value is that returned by the system shell after running command. The shell is given by the Windows environment variable
COMSPEC
: it is usually cmd.exe, which returns the exit status of the command run; on systems using a non-native shell, consult your shell documentation.The
subprocess
module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in thesubprocess
documentation for some helpful recipes.Disponibilidade: Unix, Windows.
-
os.
times
()¶ Returns the current global process times. The return value is an object with five attributes:
user
- user timesystem
- system timechildren_user
- user time of all child processeschildren_system
- system time of all child processeselapsed
- elapsed real time since a fixed point in the past
For backwards compatibility, this object also behaves like a five-tuple containing
user
,system
,children_user
,children_system
, andelapsed
in that order.See the Unix manual page times(2) or the corresponding Windows Platform API documentation. On Windows, only
user
andsystem
are known; the other attributes are zero.Disponibilidade: Unix, Windows.
Alterado na versão 3.3: Retorna tupla alterada de uma tupla para um objeto tipo tupla com atributos nomeados.
-
os.
wait
()¶ Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.
Disponibilidade: Unix.
-
os.
waitid
(idtype, id, options)¶ Wait for the completion of one or more child processes. idtype can be
P_PID
,P_PGID
orP_ALL
. id specifies the pid to wait on. options is constructed from the ORing of one or more ofWEXITED
,WSTOPPED
orWCONTINUED
and additionally may be ORed withWNOHANG
orWNOWAIT
. The return value is an object representing the data contained in thesiginfo_t
structure, namely:si_pid
,si_uid
,si_signo
,si_status
,si_code
orNone
ifWNOHANG
is specified and there are no children in a waitable state.Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
P_PID
¶ -
os.
P_PGID
¶ -
os.
P_ALL
¶ These are the possible values for idtype in
waitid()
. They affect how id is interpreted.Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
WEXITED
¶ -
os.
WSTOPPED
¶ -
os.
WNOWAIT
¶ Flags that can be used in options in
waitid()
that specify what child signal to wait for.Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
CLD_EXITED
¶ -
os.
CLD_DUMPED
¶ -
os.
CLD_TRAPPED
¶ -
os.
CLD_CONTINUED
¶ These are the possible values for
si_code
in the result returned bywaitid()
.Disponibilidade: Unix.
Novo na versão 3.3.
-
os.
waitpid
(pid, options)¶ The details of this function differ on Unix and Windows.
On Unix: Wait for completion of a child process given by process id pid, and return a tuple containing its process id and exit status indication (encoded as for
wait()
). The semantics of the call are affected by the value of the integer options, which should be0
for normal operation.If pid is greater than
0
,waitpid()
requests status information for that specific process. If pid is0
, the request is for the status of any child in the process group of the current process. If pid is-1
, the request pertains to any child of the current process. If pid is less than-1
, status is requested for any process in the process group-pid
(the absolute value of pid).An
OSError
is raised with the value of errno when the syscall returns -1.On Windows: Wait for completion of a process given by process handle pid, and return a tuple containing pid, and its exit status shifted left by 8 bits (shifting makes cross-platform use of the function easier). A pid less than or equal to
0
has no special meaning on Windows, and raises an exception. The value of integer options has no effect. pid can refer to any process whose id is known, not necessarily a child process. Thespawn*
functions called withP_NOWAIT
return suitable process handles.Alterado na versão 3.5: Se a chamada de sistema é interrompida e o tratador de sinal não levanta uma exceção, a função agora tenta novamente a chamada de sistema em vez de levantar uma exceção
InterruptedError
(consulte PEP 475 para entender a lógica).
-
os.
wait3
(options)¶ Similar to
waitpid()
, except no process id argument is given and a 3-element tuple containing the child’s process id, exit status indication, and resource usage information is returned. Refer toresource
.getrusage()
for details on resource usage information. The option argument is the same as that provided towaitpid()
andwait4()
.Disponibilidade: Unix.
-
os.
wait4
(pid, options)¶ Similar to
waitpid()
, except a 3-element tuple, containing the child’s process id, exit status indication, and resource usage information is returned. Refer toresource
.getrusage()
for details on resource usage information. The arguments towait4()
are the same as those provided towaitpid()
.Disponibilidade: Unix.
-
os.
WNOHANG
¶ The option for
waitpid()
to return immediately if no child process status is available immediately. The function returns(0, 0)
in this case.Disponibilidade: Unix.
-
os.
WCONTINUED
¶ This option causes child processes to be reported if they have been continued from a job control stop since their status was last reported.
Availability: some Unix systems.
-
os.
WUNTRACED
¶ This option causes child processes to be reported if they have been stopped but their current state has not been reported since they were stopped.
Disponibilidade: Unix.
The following functions take a process status code as returned by
system()
, wait()
, or waitpid()
as a parameter. They may be
used to determine the disposition of a process.
-
os.
WCOREDUMP
(status)¶ Return
True
if a core dump was generated for the process, otherwise returnFalse
.Disponibilidade: Unix.
-
os.
WIFCONTINUED
(status)¶ Return
True
if the process has been continued from a job control stop, otherwise returnFalse
.Disponibilidade: Unix.
-
os.
WIFSTOPPED
(status)¶ Return
True
if the process has been stopped, otherwise returnFalse
.Disponibilidade: Unix.
-
os.
WIFSIGNALED
(status)¶ Return
True
if the process exited due to a signal, otherwise returnFalse
.Disponibilidade: Unix.
-
os.
WIFEXITED
(status)¶ Return
True
if the process exited using the exit(2) system call, otherwise returnFalse
.Disponibilidade: Unix.
-
os.
WEXITSTATUS
(status)¶ If
WIFEXITED(status)
is true, return the integer parameter to the exit(2) system call. Otherwise, the return value is meaningless.Disponibilidade: Unix.
-
os.
WSTOPSIG
(status)¶ Return the signal which caused the process to stop.
Disponibilidade: Unix.
-
os.
WTERMSIG
(status)¶ Return the signal which caused the process to exit.
Disponibilidade: Unix.
16.1.7. Interface to the scheduler¶
These functions control how a process is allocated CPU time by the operating system. They are only available on some Unix platforms. For more detailed information, consult your Unix manpages.
Novo na versão 3.3.
The following scheduling policies are exposed if they are supported by the operating system.
-
os.
SCHED_OTHER
¶ The default scheduling policy.
-
os.
SCHED_BATCH
¶ Scheduling policy for CPU-intensive processes that tries to preserve interactivity on the rest of the computer.
-
os.
SCHED_IDLE
¶ Scheduling policy for extremely low priority background tasks.
-
os.
SCHED_SPORADIC
¶ Scheduling policy for sporadic server programs.
-
os.
SCHED_FIFO
¶ A First In First Out scheduling policy.
-
os.
SCHED_RR
¶ A round-robin scheduling policy.
-
os.
SCHED_RESET_ON_FORK
¶ This flag can be OR’ed with any other scheduling policy. When a process with this flag set forks, its child’s scheduling policy and priority are reset to the default.
-
class
os.
sched_param
(sched_priority)¶ This class represents tunable scheduling parameters used in
sched_setparam()
,sched_setscheduler()
, andsched_getparam()
. It is immutable.Neste momento, há somente um único parâmetro possível:
-
sched_priority
¶ A prioridade de agendamento para uma política de agendamento.
-
-
os.
sched_get_priority_min
(policy)¶ Get the minimum priority value for policy. policy is one of the scheduling policy constants above.
-
os.
sched_get_priority_max
(policy)¶ Get the maximum priority value for policy. policy is one of the scheduling policy constants above.
-
os.
sched_setscheduler
(pid, policy, param)¶ Set the scheduling policy for the process with PID pid. A pid of 0 means the calling process. policy is one of the scheduling policy constants above. param is a
sched_param
instance.
-
os.
sched_getscheduler
(pid)¶ Return the scheduling policy for the process with PID pid. A pid of 0 means the calling process. The result is one of the scheduling policy constants above.
-
os.
sched_setparam
(pid, param)¶ Set a scheduling parameters for the process with PID pid. A pid of 0 means the calling process. param is a
sched_param
instance.
-
os.
sched_getparam
(pid)¶ Return the scheduling parameters as a
sched_param
instance for the process with PID pid. A pid of 0 means the calling process.
-
os.
sched_rr_get_interval
(pid)¶ Return the round-robin quantum in seconds for the process with PID pid. A pid of 0 means the calling process.
-
os.
sched_yield
()¶ Libera a CPU voluntariamente.
-
os.
sched_setaffinity
(pid, mask)¶ Restrict the process with PID pid (or the current process if zero) to a set of CPUs. mask is an iterable of integers representing the set of CPUs to which the process should be restricted.
-
os.
sched_getaffinity
(pid)¶ Return the set of CPUs the process with PID pid (or the current process if zero) is restricted to.
16.1.8. Diversas Informações de Sistema¶
-
os.
confstr
(name)¶ Return string-valued system configuration values. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given as the keys of the
confstr_names
dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted.Se o valor de configuração especificado por name não for definido, retorna
None
.If name is a string and is not known,
ValueError
is raised. If a specific value for name is not supported by the host system, even if it is included inconfstr_names
, anOSError
is raised witherrno.EINVAL
for the error number.Disponibilidade: Unix.
-
os.
confstr_names
¶ Dictionary mapping names accepted by
confstr()
to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.Disponibilidade: Unix.
-
os.
cpu_count
()¶ Retorna o número de CPUs do sistema. Retorna
None
se não determinado.Novo na versão 3.4.
-
os.
getloadavg
()¶ Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes or raises
OSError
if the load average was unobtainable.Disponibilidade: Unix.
-
os.
sysconf
(name)¶ Return integer-valued system configuration values. If the configuration value specified by name isn’t defined,
-1
is returned. The comments regarding the name parameter forconfstr()
apply here as well; the dictionary that provides information on the known names is given bysysconf_names
.Disponibilidade: Unix.
-
os.
sysconf_names
¶ Dictionary mapping names accepted by
sysconf()
to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.Disponibilidade: Unix.
Os dados a seguir são usados para suportar operações de manipulação de path. Estão definidos e disponíveis para todas as plataformas.
Higher-level operations on pathnames are defined in the os.path
module.
-
os.
curdir
¶ The constant string used by the operating system to refer to the current directory. This is
'.'
for Windows and POSIX. Also available viaos.path
.
-
os.
pardir
¶ The constant string used by the operating system to refer to the parent directory. This is
'..'
for Windows and POSIX. Also available viaos.path
.
-
os.
sep
¶ The character used by the operating system to separate pathname components. This is
'/'
for POSIX and'\\'
for Windows. Note that knowing this is not sufficient to be able to parse or concatenate pathnames — useos.path.split()
andos.path.join()
— but it is occasionally useful. Also available viaos.path
.
-
os.
altsep
¶ An alternative character used by the operating system to separate pathname components, or
None
if only one separator character exists. This is set to'/'
on Windows systems wheresep
is a backslash. Also available viaos.path
.
-
os.
extsep
¶ The character which separates the base filename from the extension; for example, the
'.'
inos.py
. Also available viaos.path
.
-
os.
pathsep
¶ The character conventionally used by the operating system to separate search path components (as in
PATH
), such as':'
for POSIX or';'
for Windows. Also available viaos.path
.
-
os.
defpath
¶ The default search path used by
exec*p*
andspawn*p*
if the environment doesn’t have a'PATH'
key. Also available viaos.path
.
-
os.
linesep
¶ The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as
'\n'
for POSIX, or multiple characters, for example,'\r\n'
for Windows. Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single'\n'
instead, on all platforms.
-
os.
devnull
¶ The file path of the null device. For example:
'/dev/null'
for POSIX,'nul'
for Windows. Also available viaos.path
.
-
os.
RTLD_LAZY
¶ -
os.
RTLD_NOW
¶ -
os.
RTLD_GLOBAL
¶ -
os.
RTLD_LOCAL
¶ -
os.
RTLD_NODELETE
¶ -
os.
RTLD_NOLOAD
¶ -
os.
RTLD_DEEPBIND
¶ Flags for use with the
setdlopenflags()
andgetdlopenflags()
functions. See the Unix manual page dlopen(3) for what the different flags mean.Novo na versão 3.3.
16.1.9. Miscellaneous Functions¶
-
os.
urandom
(n)¶ Return a string of n random bytes suitable for cryptographic use.
This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation.
On Linux,
getrandom()
syscall is used if available and the urandom entropy pool is initialized (getrandom()
does not block). On a Unix-like system this will query/dev/urandom
. On Windows, it will useCryptGenRandom()
. If a randomness source is not found,NotImplementedError
will be raised.For an easy-to-use interface to the random number generator provided by your platform, please see
random.SystemRandom
.Alterado na versão 3.5.2: On Linux, if
getrandom()
blocks (the urandom entropy pool is not initialized yet), fall back on reading/dev/urandom
.Alterado na versão 3.5: On Linux 3.17 and newer, the
getrandom()
syscall is now used when available. On OpenBSD 5.6 and newer, the Cgetentropy()
function is now used. These functions avoid the usage of an internal file descriptor.