Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use print() function in both Python 2 and Python 3 #925

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions Ghidra/Extensions/SleighDevTools/pcodetest/build.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
import os
import shutil
import subprocess
Expand Down Expand Up @@ -27,7 +28,7 @@ def run(self, cmd, stdout=False, stderr=False, verbose=True):
else:
str = ' '.join(cmd);
if stdout:
f = file(stdout, 'w+')
f = open(stdout, 'w+')
str += ' 1>%s 2>&1' % (stdout)
else:
f = subprocess.PIPE
Expand Down Expand Up @@ -176,9 +177,9 @@ def log_open(self, name):
def log_close(self):
if self.log:
if self.num_errors > 0:
print '# ERROR: There were errors, see %s' % self.name
print('# ERROR: There were errors, see %s' % self.name)
elif self.num_warnings > 0:
print '# WARNING: There were warnings, see %s' % self.name
print('# WARNING: There were warnings, see %s' % self.name)
self.log.close()
self.log = False
self.name = False
Expand All @@ -190,7 +191,7 @@ def log_pr(self, what):
self.log.write(what + '\n')
self.log.flush()
else:
print what
print(what)
sys.stdout.flush()

def log_err(self, what):
Expand Down Expand Up @@ -271,7 +272,7 @@ def format(self, val):
if isinstance(val, basestring) and '%' in val:
return val % self.__dict__
elif isinstance(val, dict):
return dict(map(lambda (k,v): (k,self.format(v)), val.iteritems()))
return dict(map(lambda k,v: (k,self.format(v)), val.iteritems()))
else: return val

def __getattr__(self, attr):
Expand Down
5 changes: 3 additions & 2 deletions Ghidra/Extensions/SleighDevTools/pcodetest/pcodetest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
import os
import glob
import re
Expand Down Expand Up @@ -41,8 +42,8 @@ def print_all(cls):
pct = sorted(cls.list.iteritems(), key=lambda x: x[0].lower())

for t,pcodetest in sorted(cls.list.iteritems(), key=lambda x: x[0].lower()):
print str(pcodetest)
if pcodetest.config.verbose: print pcodetest.config.dump()
print(str(pcodetest))
if pcodetest.config.verbose: print(pcodetest.config.dump())

def __str__(self):
cb = 'build-all:%-5s' % ('yes' if self.config.build_all else 'no')
Expand Down
11 changes: 6 additions & 5 deletions Ghidra/Features/Base/ghidra_scripts/RecursiveStringFinder.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
#Given a function, find all strings used within all called funtions.
# @category: Strings

Expand Down Expand Up @@ -69,11 +70,11 @@ def getName(self):
def process(self, processed=[]):
if self.fn is None:
return processed
print "Processing %s -> %s" % (str(self.fromAddr), str(self.toAddr))
print("Processing %s -> %s" % (str(self.fromAddr), str(self.toAddr)))
if self.getName() in processed:
return processed
addresses = self.getAddresses()
print str(type(addresses))
print(str(type(addresses)))
while addresses.hasNext():
#for a in addresses:
a = addresses.next()
Expand Down Expand Up @@ -133,14 +134,14 @@ def getReferences(insn):

bigfunc = getFunctionContaining(currentAddress)
if bigfunc is None:
print "Please place the cursor within a function!"
print("Please place the cursor within a function!")
else:
AddrSetView = bigfunc.getBody()
func = FunctionNode(None, AddrSetView.getMinAddress())
func.process()
print str(func.indentedString())
print(str(func.indentedString()))
#findStrings(func)
print "Done!"
print("Done!")



Expand Down
7 changes: 4 additions & 3 deletions Ghidra/Features/Base/ghidra_scripts/mark_in_out.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
# Sets up IOPORT IN/OUT references for the Program
#@category Instructions
# Before running this script, you should have created an OVERLAY memory
Expand All @@ -15,15 +16,15 @@ def add_io_reference(instruction, opIndex, refType):
of the given instruction."""
# delete all current references from the port address field
for ref in refMgr.getReferences(instruction.address, opIndex):
print " Deleting reference to address", ref.toAddress
print(" Deleting reference to address", ref.toAddress)
refMgr.delete(ref)
# must use int() to avoid creating a long...
# we only have 16 bits of I/O address space, and a long
# would append an 'L' to the hex address
ioAddr = int(instruction.getOpObjects(opIndex)[0].value)
ioAddress = addrFactory.getAddress("IOMEM::" + hex(ioAddr))
print " Adding", refType, "reference from", instruction.address, \
"to address", ioAddress
print(" Adding", refType, "reference from", instruction.address, \
"to address", ioAddress)
# from, to, type, sourceType, opIndex
refMgr.addMemoryReference(instruction.address, ioAddress,
refType, ANALYSIS, opIndex)
Expand Down
39 changes: 20 additions & 19 deletions Ghidra/Features/Python/ghidra_scripts/AskScriptPy.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
# An example of asking for user input.

# Note the ability to pre-populate values for some of these variables when AskScript.properties file exists.
Expand Down Expand Up @@ -25,65 +26,65 @@
# corresponding askXxx() method in the GhidraScript.
try:
file1 = askFile("FILE", "Choose file:")
print "file was: " + str(file1)
print("file was: " + str(file1))

directory1 = askDirectory("Directory", "Choose directory:")
print "directory was: " + str(directory1)
print("directory was: " + str(directory1))

lang = askLanguage("Language Picker", "I want this one!")
print "language was: " + lang.toString()
print("language was: " + lang.toString())

domFolder = askProjectFolder("Please pick a domain folder!")
print "domFolder was: " + domFolder.getName()
print("domFolder was: " + domFolder.getName())

int1 = askInt("integer 1", "enter integer 1")
int2 = askInt("integer 2", "enter integer 2")
print "int1 + int2 = " + str(int1 + int2)
print("int1 + int2 = " + str(int1 + int2))

long1 = askLong("long 1", "enter long 1")
long2 = askLong("long 2", "enter long 2")
print "long1 + long2 = " + str(long1 + long2)
print("long1 + long2 = " + str(long1 + long2))

address1 = askAddress("address 1", "enter address 1")
address2 = askAddress("address 2", "enter address 2")
print "address1 + address2 = " + address1.add(address2.getOffset()).toString()
print("address1 + address2 = " + address1.add(address2.getOffset()).toString())

#bytes = askBytes("bytes", "enter byte pattern")
#for b in bytes:
# print "b = " + str(b & 0xff)

prog = askProgram("Please choose a program to open.")
print "Program picked: " + prog.getName()
print("Program picked: " + prog.getName())

domFile = askDomainFile("Which domain file would you like?")
print "Domain file: " + domFile.getName()
print("Domain file: " + domFile.getName())

d1 = askDouble("double 1", "enter double 1")
d2 = askDouble("double 2", "enter double 2")
print "d1 + d2 = " + str(d1 + d2)
print("d1 + d2 = " + str(d1 + d2))

myStr = askString("String Specification", "Please type a string: ")
myOtherStr = askString("Another String Specification", "Please type another string: ", "replace me!")
print "You typed: " + myStr + " and " + myOtherStr
print("You typed: " + myStr + " and " + myOtherStr)

choice = askChoice("Choice", "Please choose one", [ "grumpy", "dopey", "sleepy", "doc", "bashful" ], "bashful")
print "Choice? " + choice
print("Choice? " + choice)

choices1 = askChoices("Choices 1", "Please choose one or more numbers.", [ 1, 2, 3, 4, 5, 6 ])
print "Choices 1: "
print("Choices 1: ")
for intChoice in choices1:
print str(intChoice) + " "
print ""
print(str(intChoice) + " ")
print("")

choices2 = askChoices("Choices 2", "Please choose one or more of the following.",
[ 1.1, 2.2, 3.3, 4.4, 5.5, 6.6 ], ["Part 1", "Part 2", "Part 3", "Part 4", "Part 5", "Part 6" ])
print "Choices 2: "
print("Choices 2: ")
for intChoice in choices2:
print str(intChoice) + " "
print ""
print(str(intChoice) + " ")
print("")

yesOrNo = askYesNo("yes or no", "is this a yes/no question?")
print "Yes or No? " + str(yesOrNo)
print("Yes or No? " + str(yesOrNo))

except IllegalArgumentException as error:
Msg.warn(self, "Error during headless processing: " + error.toString())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
# Example of a script prompting the user for a data type.

# DISCLAIMER: This is a recreation of a Java Ghidra script for example
Expand All @@ -18,4 +19,4 @@
tool.showDialog(selectionDialog)
dataType = selectionDialog.getUserChosenDataType()
if dataType is not None:
print "Chosen data type: " + str(dataType)
print("Chosen data type: " + str(dataType))
5 changes: 3 additions & 2 deletions Ghidra/Features/Python/ghidra_scripts/ExampleColorScriptPy.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
# An example of how to color the listing background

# DISCLAIMER: This is a recreation of a Java Ghidra script for example
Expand All @@ -14,13 +15,13 @@

service = state.getTool().getService(ColorizingService)
if service is None:
print "Can't find ColorizingService service"
print("Can't find ColorizingService service")
if currentSelection is not None:
service.setBackgroundColor(currentSelection, Color(255, 200, 200))
elif currentAddress is not None:
service.setBackgroundColor(currentAddress, currentAddress, Color(255, 200, 200))
else:
print "No selection or current address to color"
print("No selection or current address to color")

anotherAddress = currentAddress.add(10)
setBackgroundColor(anotherAddress, Color.YELLOW)
Expand Down
21 changes: 11 additions & 10 deletions Ghidra/Features/Python/ghidra_scripts/FormatExampleScriptPy.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
# An example using the Python string formatting.
# See FormatExampleScript.java for examples of using the printf() method.

Expand All @@ -9,20 +10,20 @@
from time import *
import java.util.Calendar

print "The %s jumped over the %s" % ("cow", "moon")
print("The %s jumped over the %s" % ("cow", "moon"))

print "The %s jumped over the %s " % ("cow", "moon") + strftime("%X")
print("The %s jumped over the %s " % ("cow", "moon") + strftime("%X"))

print "The %s jumped over the %s - timestamp: %s" % ("cow", "moon", strftime("%c %Z"))
print("The %s jumped over the %s - timestamp: %s" % ("cow", "moon", strftime("%c %Z")))

print "The %s jumped over the %s at %s on %s" % ("cow", "moon", strftime("%I:%M%p"), strftime("%A, %b %d"))
print("The %s jumped over the %s at %s on %s" % ("cow", "moon", strftime("%I:%M%p"), strftime("%A, %b %d")))

print "Padding: %03d" % (1)
print("Padding: %03d" % (1))

print "Hex: 0x%x" % (10)
print("Hex: 0x%x" % (10))

print "Left-justified: %-10d" % (1)
print "Right-justified: %10d" % (1)
print("Left-justified: %-10d" % (1))
print("Right-justified: %10d" % (1))

print "String fill: '%10s'" % ("Fill")
print "String fill, left justified: '%-10s'" % ("Fill")
print("String fill: '%10s'" % ("Fill"))
print("String fill, left justified: '%-10s'" % ("Fill"))
3 changes: 2 additions & 1 deletion Ghidra/Features/Python/ghidra_scripts/ImportSymbolsScript.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
#Imports a file with lines in the form "symbolName 0xADDRESS"
#@category Data
#@author
Expand All @@ -7,5 +8,5 @@
for line in file(f.absolutePath): # note, cannot use open(), since that is in GhidraScript
pieces = line.split()
address = toAddr(long(pieces[1], 16))
print "creating symbol", pieces[0], "at address", address
print("creating symbol", pieces[0], "at address", address)
createLabel(address, pieces[0], False)
3 changes: 2 additions & 1 deletion Ghidra/Features/Python/ghidra_scripts/PrintNonZeroPurge.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import print_function
# Prints out all the functions in the program that have a non-zero stack purge size

for func in currentProgram.getFunctionManager().getFunctions(currentProgram.evaluateAddress("0"), 1):
if func.getStackPurgeSize() != 0:
print "Function", func, "at", func.getEntryPoint(), "has nonzero purge size", func.getStackPurgeSize()
print("Function", func, "at", func.getEntryPoint(), "has nonzero purge size", func.getStackPurgeSize())
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
from __future__ import print_function
# Example of being imported by a Ghidra Python script/module
# @category: Examples.Python

# The following line will fail if this module is imported from external_module_caller.py,
# because only the script that gets directly launched by Ghidra inherits fields and methods
# from the GhidraScript/FlatProgramAPI.
try:
print currentProgram.getName()
print(currentProgram.getName())
except NameError:
print "Failed to get the program name"
print("Failed to get the program name")

# The Python module that Ghidra directly launches is always called __main__. If we import
# everything from that module, this module will behave as if Ghidra directly launched it.
from __main__ import *

# The below method call should now work
print currentProgram.getName()
print(currentProgram.getName())

25 changes: 13 additions & 12 deletions Ghidra/Features/Python/ghidra_scripts/ghidra_basics.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,38 @@
from __future__ import print_function
# Examples of basic Ghidra scripting in Python
# @category: Examples.Python

# Get info about the current program
print
print "Program Info:"
print()
print("Program Info:")
program_name = currentProgram.getName()
creation_date = currentProgram.getCreationDate()
language_id = currentProgram.getLanguageID()
compiler_spec_id = currentProgram.getCompilerSpec().getCompilerSpecID()
print "%s: %s_%s (%s)\n" % (program_name, language_id, compiler_spec_id, creation_date)
print("%s: %s_%s (%s)\n" % (program_name, language_id, compiler_spec_id, creation_date))

# Get info about the current program's memory layout
print "Memory layout:"
print "Imagebase: " + hex(currentProgram.getImageBase().getOffset())
print("Memory layout:")
print("Imagebase: " + hex(currentProgram.getImageBase().getOffset()))
for block in getMemoryBlocks():
start = block.getStart().getOffset()
end = block.getEnd().getOffset()
print "%s [start: 0x%x, end: 0x%x]" % (block.getName(), start, end)
print
print("%s [start: 0x%x, end: 0x%x]" % (block.getName(), start, end))
print()

# Get the current program's function names
function = getFirstFunction()
while function is not None:
print function.getName()
print(function.getName())
function = getFunctionAfter(function)
print
print()

# Get the address of the current program's current location
print "Current location: " + hex(currentLocation.getAddress().getOffset())
print("Current location: " + hex(currentLocation.getAddress().getOffset()))

# Get some user input
val = askString("Hello", "Please enter a value")
print val
print(val)

# Output to a popup window
popup(val)
Expand All @@ -50,7 +51,7 @@
selectionDialog = DataTypeSelectionDialog(tool, dtm, -1, AllowedDataTypes.FIXED_LENGTH)
tool.showDialog(selectionDialog)
dataType = selectionDialog.getUserChosenDataType()
if dataType != None: print "Chosen data type: " + str(dataType)
if dataType != None: print("Chosen data type: " + str(dataType))

# Report progress to the GUI. Do this in all script loops!
import time
Expand Down
Loading