Evaluating code after parsing it - python-2.7

I'm trying to create a tool written in Python that executes R scripts (from files), injecting values into variables before executing them and reading output variables after that.
The rinterface documentation mentions the parse function, but there is no indication about how to execute the result. The C interface contains an eval function but it doesn't seem available in Python.
Here's a very basic example of what I want to do :
import rpy2.rinterface as ri
ri.initr()
with open('script.r', 'r') as myFile:
script = myFile.read()
expr = ri.parse(script)
# prepare
ri.globalenv['input'] = ri.IntSexpVector((1, 2, 3, 4))
# execute
#??????????????????
# what to do here ?
#??????????????????
# fetch results
# The script is supposed to store results into a global var named 'output'
result = ri.globalenv['output']
Thanks

There are several ways.
One is:
from rpy2.robjects.packages import importr
base = importr('base')
base.eval(expr)

Related

How to get a row from a file that starts with multiple prefixes

I'm trying to get the rows that starts with 's1', 's2'. Below is the code.
import os
f = open("test.csv","r")
lines = f.readlines()
f.close()
f = open("test.csv","w")
for line in lines:
if (line.startsWith("s1") || line.startsWith("s2"))
f.write(line)
f.close()
When I run this script I'm getting syntax error near '||'.
I looked into this link and made changes accordingly -
How to check if a string starts with one of several prefixes?
Please let me know if I'm doing anything wrong.
FYI, I'm using Python 2.7.
Thanks!

How to run a Powershell function through a Python script

I am trying to create a translator-type program in Python (this is 2.7, if that is important). I want to receive user input, translate it, and then print their output to the screen. That part is not difficult, but I also want to export it to a text file. I am using Powershell for that, with the subprocess module. The Powershell script is very short, and all it does is asks for the user to copy and paste the Python translation into an input. It then calls New-Item to create a file and gives it the value option as the Python translation.
Python code:
def translator:
inquiry = raw_input("Leetspeak trans query: ") #Enter query
inquiry = inquiry.lower() #Change all to lowercase, so that everything gets translated
newPrint1 = "" #The new string that gets returned to them at the end
level = raw_input("What type of 1337 do you want? 1 for basic, 2 for intermediate, \
3 for intermediate-advanced, and 4 for ultimate.")
if level == "1":
from b4s1c_l33t import leetkey
elif level == "2":
from In73rm3d1473_1337 import leetkey
elif level == "3":
from In7_4DV import leetkey
from In7_4DV import combokey
elif level == "4":
from U17IM473_1337 import leetkey
from U17IM473_1337 import combokey
for char in inquiry:
if char in leetkey:
newPrint1 += leetkey[char]
else:
newPrint1 += char #Checks to see if the char is in the single-char list, then appends it accordingly
if int(level) >= 3:
for item in combokey:
if item in newPrint1:
newPrint1 = newPrint1.replace(item, combokey[item])
print newPrint1 #Print answer
question = raw_input(r"Do you want to translate some more? Type Y or N ") #Asks if they want to do more
question = question.lower() #Changes it to lowercase, for sending through the if loop
if question == "y" or question == "Y":
translator() #If answer is yes, program calls the entire function again
elif question != "y" and question != "n" and question != "Y" and question != "N":
print "I didn't quite catch that."
ps = raw_input("Would you like to export your leetness to a file? Type Y or N ")
if ps == "Y" or ps == "y":
import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./1337Export.ps1\";", "&export"])
else:
print r"0|<. 600|)|3`/3!"
translator() #calls the function once
Powershell script:
Function export(){
$param = Read-Host("Copy-paste the translation from above here! ")
New-Item C:\Scripts\1337\1337ness.txt -type file -value $param
}
But I also know that the script was working perfectly up until I added the Powershell to it, so the problem is either in my usage of the subprocess module or in the Powershell script itself. I am a somewhat-medium-beginner at using Powershell, so any help will be greatly appreciated. Either that, or if there is a way to create the new file and write data to it in Python itself, that would be greatly appreciated.
Thanks,
Prem
Note: in the Python script, the leetkey and combokey are in separate files that are imported based on the value of the variable level.
UPDATE: I looked at the page here, and the subprocess code in the Python script is what I found in that page. It did not work, but instead threw an error saying that the export function does not exist, which it obviously does... in Powershell. Thanks again!
Your parameter construction is off. You want to run the following commandline in PowerShell:
. "./1337Export.ps1"; & export
which basically means "dot-source (IOW import) the script 1337Export.ps1 from the current working directory, then call (&) the function export".
The cleanest way to do this is to put the statement in a scriptblock:
&{. "./1337Export.ps1"; & export}
and pass that scriptblock as a single argument, so your Python statement should look like this:
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", '-Command', '&{. "./1337Export.ps1"; & export}'])
Of course you need to make sure that 1337Export.ps1 actually exists in the current working directory when you execute the Python script.
You have to do two things:
1) dot source the script (which is similar to python's import), and
2) subprocess.call.
import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePS\";", "&export"])
Note: I have assumed that both the .py and .ps1 are residing in the same directory and the name of the powershell script is "SamplePS" and from that script I am using the function "export"
Hope it helps

Handling map function in python2 & python3

Recently i came across a question & confused with a possible solution,
code part is
// code part in result reader
result = map(int, input())
// consumer call
result_consumer(result)
its not about how do they work, the problem is when you are running in python2 it will raise an exception, on result fetching part, so result reader can handle the exception, but incase of python3 a map object is returned, so only consumer will be able to handle exception.
is there any solution keeping map function & handle the exception in python2 & python3
python3
>>> d = map(int, input())
1,2,3,a
>>> d
<map object at 0x7f70b11ee518>
>>>
python2
>>> d = map(int, input())
1,2,3,'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
>>>
the behavior of map is not the only difference between python2 and python3, input is also difference, you need to keep in mind the basic differences between the two to make code compatible for both
python 3 vs python 2
map = itertools.imap
zip = itertools.izip
filter = itertools.ifilter
range = xrange
input = raw_input
so to make code for both, you can use alternatives like list comprehension that work the same for both, and for those that don't have easy alternatives, you can make new functions and/or use conditional renames, like for example
my_input = input
try:
raw_input
except NameError: #we are in python 3
my_input = lambda msj=None: eval(input(msj))
(or with your favorite way to check which version of python is in execution)
# code part in result reader
result = [ int(x) for x in my_input() ]
# consumer call
result_consumer(result)
that way your code do the same regardless of which version of python you run it.
But as jsbueno mentioned, eval and python2's input are dangerous so use the more secure raw_input or python3's input
try:
input = raw_input
except NameError: #we are in python 3
pass
(or with your favorite way to check which version of python is in execution)
then if your plan is to provide your input as 1,2,3 add an appropriate split
# code part in result reader
result = [ int(x) for x in input().split(",") ]
# consumer call
result_consumer(result)
If you always need the exception to occur at the same place you can always force the map object to yield its results by wrapping it in a list call:
result = list(map(int, input()))
If an error occurs in Python 2 it will be during the call to map while, in Python 3, the error is going to surface during the list call.
The slight downside is that in the case of Python 2 you'll create a new list. To avoid this you could alternatively branch based on sys.version and use the list only in Python 3 but that might be too tedious for you.
I usually use my own version of map in this situations to escape any possible problem may occur and it's
def my_map(func,some_list):
done = []
for item in some_list:
done.append( func(item) )
return done
and my own version of input too
def getinput(text):
import sys
ver = sys.version[0]
if ver=="3":
return input(text)
else:
return raw_input(text)
if you are working on a big project add them to a python file and import them any time you need like what I do.

Use Python command line argument as function names and function values

Related to this question Command line arguments in python.
With the SYS module, how can I use a command line argument as a function name and function value, within my code - without importing some other module?
I'd like a solution that uses sys only. Also, please no variable-length params answers. Those are confusing. Assume that just the function name and one function variable are specified at the command line.
import sys
def reversal(aaa): return aaa[::-1]
a = sys.argv[1]
b = sys.argv[2]
print a(b)
At the command line
cpu_location$ python blah.py reversal 'abcdefg'
Traceback (most recent call last):
File "blah.py", line 8, in <module>
print a(b)
TypeError: 'str' object is not callable
I want to know how to make sys.argv[1] be considered a function name, thereby calling the function I have defined.
The other posts I see on this are a mash up of:
- dealing with C/C++ and adding some other module
- not using sys at all
- using the argv items as values for functions, and names of other files, instead of names of functions
Better than the eval solution would be:
a = globals()[sys.argv[1]]
a(b)
globals() returns a dictionary mapping global variables names to those global variables. So globals()['reversal'] evaluates to the reversal function.
It's safer than the eval function. With your approach you could do something like:
python blah.py 'lambda x: x+"hi"' foobar
Which would print foobarhi, which is unexpected because that's not a function name.
2 hours later, I find the answer. I think it's worth it to post it here in a very simple fashion.
Basiclaly there is no "function" data type in Python, but someone did mention a function eval, which is built-in. Execute python commands passed as strings in command line using python -c (No -c is needed for my own example)
The solution, is to change
a = sys.argv[1]
to
a = eval(sys.argv[1])
This will make the passed in word, reversal, be evaluated. It will evaluate to a function. Then the a(b) call will be a perfect call of a function on a string, like how it's defined. Output will be like:
cpu_location$ python blah.py reversal unquoted
detouqnu
cpu_location$ python blah.py reversal 'withquotes'
setouqhtiw
use google module: fire
pip install fire
Here's a simple example:
import fire
class Calculator(object):
"""A simple calculator class."""
def double(self, number):
return 2 * number
if __name__ == '__main__':
fire.Fire(Calculator)
Then, from the command line, you can run:
python calculator.py double 10 # 20
python calculator.py double --number=15 # 30

Beginner, python - how to read a list from a file

I have a Word document that is literally a list of lists, that is 8 pages long. Eg:
[['WTCS','Dec 21'],['THWD','Mar 22']...]
I am using Linux Mint, Python 3.2 and the IDLE interface, plus my own .py programs. I need to read and reference this list frequently and when I stored it inside .py programs it seemed to slow down the window considerably as I was editing code. How can I store this information in a separate file and read it into python? I have it in a .txt file now and tried the following code:
def readlist():
f = open(r'/home/file.txt','r')
info = list(f.read())
return(info)
but I get each character as an element of a list. I also tried info = f.read() but I get a string. Thanks!
You can convert a Python list read from a text file from a text file as a string into a list using the ast module:
>>> import ast
>>> s = "[['WTCS','Dec 21'],['THWD','Mar 22']]"
>>> ast.literal_eval(s)
[['WTCS', 'Dec 21'], ['THWD', 'Mar 22']]