Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

Perl to Python functions translation map

News Scripting Languages

Best Python books for system administrators

Recommended Links Python for Perl programmers Debugging in Python Perl to Python translation
 Python installation Installing Python 3 from RPMs Installing Python Packages Compiling Python from source   Python coroutines Generators as semi-coroutines
Perl to Python functions map Control Flow Statements Execution of commands and capturing output of shell scripts and pipelines Programming environment Python Braces Debate Python IDEs Pycharm IDE
Command-Line Syntax and Options pdb — The Python Debugger Quotes Python history  Tutorials Python Cheatsheets Etc

Adapted from PERL TO PYTHON QUICK REFERENCE - Perl To Python Migration [Book]  by Martin C. Brown

With some additions and corrections

<> in scalar contest   f = x.read()  or x.readline()
in array context (slurping) text_array = x.readlines() See Python File Slurp - Stack Overflow
abs() abs()
accept() s.accept()
alarm() signal.alarm()
atan2() math.atan2(), cmath.atan2()
bind() s.bind()
binmode() N/A
bless() N/A
caller() traceback.print_tb()
chdir() os.chdir()
chmod() os.chmod()
chomp() string.rstrip()   It returns the new string with trailing whitespace removed. See Description
chop() line=line[0:-1] Various other methods available.
chown() os.chown()
chr() chr()
chroot() N/A
close() f.close(), s.close()
closedir() Use glob.glob() to get a list of files and iterate over the list
connect() s.connect()
continue N/A
cos() math.cos(), cmath.cos()
defined() array[i]==None Difficult to translate as out of bound reference to the list cause exception in Python. Custom written function needed.
delete() del  In Perl delete is applicable only to hashes. There is not delete for the lists
die() raise()
do() execfile()
dump() N/A
each() in Iterators for hashes and lists are builtin in Python. When called on a hash in list context, returns a 2-element list consisting of the key and value for the next element of a hash. 
  1. while (my ($key,$value) = each %ENV) {
  2. print "$key=$value\n";
  3. }
eof() Exception in Python. In Perl Returns 1 if the next read on FILEHANDLE will return end of file or if FILEHANDLE is not open
eval() eval(), exec()
exec() sys.exec()
exists() in Python 3.x the expression DICT in KEY  checks if key exists. Python 2.x  DICT.has_key(KEY) 
exit() sys.exit()
exp() math.exp(), cmath.exp()
fcntl() fcntl.fcntl()
fileno() f.fileno() used only for low level POSIX tty operations. 
flock() fcntl.flock()
fork os.fork()
format() print Perl uses a writing template called a 'format' to output reports. Rarely used. See Formats - Learning Perl
formline() This is an internal Perl function used by formats
getc() f.getc()
getgrent() grp.getgrall()
getgrgid() grp.getgrgid()
getgrnam() grp.getgrnam()
gethostbyaddr() socket.gethostbyaddr()
gethostbyname() socket.gethostbyname()
gethostent() N/A
getlogin() N/A
getnetbyaddr() N/A
getnetbyname() N/A
getnetent() N/A
getpeername() s.getpeername()
getpgrp os.getpgrp()
getppid os.getppid()
getpriority() N/A
getprotobyname() socket.getprotobyname()
getprotobynumber() N/A
getprotoent() N/A
getpwent() pwd.getpwall()
getpwnam() pwd.pwnam()
getpwuid() pwd.pwuid()
getservbyname() N/A
getservbyport() N/A
getservent() N/A
getsockname() s.getsockname()
getsockopt() s.getsockopt()
glob() glob.glob()
gmtime() time.gmtime()
grep() filter()
hex() eval() will work for strings of the form “0xffff” – without a leading 0x this will be interpreted as an identifier and raise an exception
import() Internal Perl function. The use function calls the import method for the package used
index() string.find()  NOTE: string.index raises exception if substring is not found
int() int()
ioctl() fcntl.ioctl()
join() string.join()
keys() dict.keys()
kill() os.kill()
last() break  Last with the label and  last with expression are not tranlatable into Python
lc() string.lower()
lcfirst() N/A
length() len()
link() os.link()
listen() s.listen()
local N/A
localtime() time.localtime()
log() math.log(), cmath.log()
lstat() os.lstat()
m// re.match(), but m//g -> re.findall()
map() map()
mkdir() os.mkdir()
my N/A
no N/A
oct() eval() will work for strings of the form “0377” – without a leading zero this will be interpreted as a decimal
open() open(), os.popen(), os.open()
opendir() Use glob.glob() to get a list of files and iterate over the list
ord() ord()
pack() struct.pack()
package NOT IMPLEMENTED. Python does not have means of creating new namespaces within main program or modules.
pipe() os.pipe()
pop() list.pop()
pos() m.pos()
print() print, f.write(), s.send()
printf() print format % tuple
prototype() N/A
push() list.append()
q/STRING/ """ ... """
qq/STRING/ """ ... """
qr// r' ... '
quotemeta() re.compile()
qw// Needs to be programmed via split method
qx// os.exec*()
rand() whrandom.random(), whrandom.randint()
read() f.read(), s.recv()
readdir() N/A
readline() f.readline()
readlink() os.readlink()
readpipe() os.read()
recv() s.recv()
redo() N/A
ref() type()
rename() os.rename()
require N/A
reset() N/A
reverse() s.reverse()
rewinddir() N/A
rindex() string.rfind() (not not string.rindex() )
rmdir() os.rmdir()
s/// re.sub(), re.subn()
say print
scalar() len
seek() os.lseek(), f.seek()
seekdir() Use glob.glob() to get a list of files and iterate over the list
select (default filehandle selection) You can redirect the standard output by re-opening sys.stdout to point to an alternative file or other filehandle object. Use sys.__stdout__ to print to the original
shift() s.pop(0)
shutdown() s.shutdown()
sin() math.sin(), cmath.sin()
sleep() time.sleep()
socket() socket.socket()
socketpair() N/A
sort() s.sort()
splice() array[x:y] = array[a,b]
split() string.split(), re.split()
sprintf() Use the format % tuple operator, which returns a formatted string
sqrt() math.sqrt(), cmath.sqrt()
srand() whrandom.seed()
stat() os.stat()
STDERR sys.stderr (original version always available in sys.__stderr__)
STDIN sys.stdin (original version always available in sys.__stdin__)
STDOUT sys.stdout (original version always available in sys.__stdout__)
study() N/A
sub def (for anonymous subroutines use the lambda statement)
substr() s[x:y]
symlink() os.symlink()
syscall() N/A
sysopen() sys.open()
sysread() f.read()
sysseek() f.sysseek()
system() os.system()
syswrite() f.write()
tell() f.tell()
telldir() N/A
tie() N/A
tied() N/A
time() time.time()
times() os.times()
tr/// string.maketrans(), string.translate()
truncate() f.truncate()
uc() string.upper()
ucfirst() string.captilize()
umask() os.umask()
undef None
unlink() os.remove(), os.unlink()
unpack() struct.unpack()
unshift() s.insert(0,x)
untie() N/A
use import
utime() os.utime()
values() dict.values()
vec() struct.pack()
wait() os.wait()
waitpid() os.waitpid()
wantarray() N/A
warn() N/A
write() sys.write(), f.write()
-X (filetests) os.access(), os.stat()

NEWS CONTENTS

Old News ;-)

https://leanpub.com/perl2python/read

Name Action
help() Invoke the built-in help system.
Number-related
abs() Return the absolute value of a number.
pow() Return power raised to a number.
round() Return the rounded floating point value.
divmod() Return a pair of numbers consisting of quotient and remainder when using integer division.
Creates Objects
ascii() Return a string containing a printable representation of an object, but escape the non-ASCII characters.
bytearray() Return a new array of bytes.
bytes() Return a new "bytes" object.
chr() Return the string representing a character.
complex() Create a complex number or convert a string or number to a complex number.
dict() Create a new dictionary.
enumerate() Return an enumerate object.
frozenset() Return a new frozenset object.
hash() Return the hash value of the object.
id() Return the "identity" of an object.
iter() Return an iterator object.
list() Return a list.
memoryview() Return a "memory view" object created from the given argument.
object() Return a new featureless object.
repr() Return a string containing a printable representation of an object.
str() Return a str version of object.
set() Return a new set object.
slice() Return a slice object.
tuple() Return a tuple
type() Return the type of an object.
Converts
bin() Convert an integer number to a binary string.
bool() Convert a value to a Boolean.
float() Convert a string or a number to floating point.
format() Convert a value to a "formatted" representation.
hex() Convert an integer number to a hexadecimal string.
int() Convert a number or string to an integer.
oct() Convert an integer number to an octal string.
ord() Return an integer representing the Unicode.
List operations
len() Return the length (the number of items) of an object.
min() Return the smallest item in an iterable.
max() Return the largest item in an iterable.
sorted() Return a new sorted list.
sum() Sums the items of an iterable from left to right and returns the total.
** Iterables **
all() Return True if all elements of the iterable are true (or if the iterable is empty).
any() Return True if any element of the iterable is true. If the iterable is empty, return False.
callable() Return True if the object argument appears callable, False if not.
map() Return an iterator that applies function to every item of iterable, yielding the results.
filter() Construct an iterator from elements of iterable for which function returns true.
zip() Make an iterator that aggregates elements from each of the iterables.
range() Return an iterable sequence.
next() Retrieve the next item from the iterator.
reversed() Return a reverse iterator.
I/O-related
dir() Return the list of names in the current local scope.
open() Open file and return a corresponding file object.
print() Print objects to the stream.
input() Reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Runs Code
compile() Compile the source into a code or AST object.
eval() The argument is parsed and evaluated as a Python expression.
exec() Dynamic execution of Python code.
Other functions
classmethod() Return a class method for the function.
getattr() Return the value of the named attribute of an object.
setattr() Assigns the value to the attribute.
delattr() Deletes the named attribute of an object.
hasattr() Return True if the name is one of the object's attributes.
globals() Return a dictionary representing the current global symbol table.
locals() Update and return a dictionary representing the current local symbol table.
isinstance() Return True if the object argument is an instance.
issubclass() Return True if class is a subclass.
property() Return a property attribute.
staticmethod() Return a static method for function.
super() Return a proxy object that delegates method calls to a parent or sibling class.
vars() Return the _dict_ attribute for a module, class, instance, or any other object.
_import_() This function is invoked by the import statement.

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

PerlPhrasebook - Python Wiki

PERL TO PYTHON QUICK REFERENCE - Perl To Python Migration [Book]

Perl To Python Migration [Book]

Perl to Python Migration Martin C. Brown 9780201734881 Amazon.com Books

Equivalents in Perl and Python



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: September 06, 2020