I'm trying to use the line magic %lprun in jupyter notebook running a python 2.7.5 kernel.
The code I'm trying to run is the following:
%load_ext line_profiler
distance = 20
veg_slope = 0
slope = 10
%lprun test = bal.run('forest', veg_slope, slope, distance, FFDI=100)
The bal.run code is a bit complicated, but executing the code with those parameters will output the following tuple:
(35.02405579440225, 'BAL-40')
However if I try to use the %lprun magic I get the following error:
File "<string>", line 1
test = bal.run(\'forest\', veg_slope, slope, distance, FFDI=100)
^
SyntaxError: unexpected character after line continuation character
Not sure what is happening there, but as a test I tried to run a simple python function like print together with the line_profiler, and that worked.
Anyone has any idea of what the problem could be?
I have just had the same issue in Jupyter / Python 3.6 using example code from a presentation available here.
I'm still a newbie but the traceback ends with the same syntax error:
File "", line 1
df[\'high_rate_normalized\'] = normalize(df, df[\'high_rate\'])
^
SyntaxError: unexpected character after line continuation character
Change to double quotes "
%lprun test = bal.run("forest", veg_slope, slope, distance, FFDI=100)
I am getting an error when I try to run this simple script:
input_variable = input("Enter your name: ")
print("your name is" + input_variable)
Let's say I type in "dude", the error I am getting is:
line 1, in <module>
input_variable = input("Enter your name: ")
File "<string>", line 1, in <module>
NameError: name 'dude' is not defined
I am running Mac OS X 10.9.1 and I am using the Python Launcher app that came with the install of Python 3.3 to run the script.
TL;DR
input function in Python 2.7, evaluates whatever your enter, as a Python expression. If you simply want to read strings, then use raw_input function in Python 2.7, which will not evaluate the read strings.
If you are using Python 3.x, raw_input has been renamed to input. Quoting the Python 3.0 release notes,
raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input())
In Python 2.7, there are two functions which can be used to accept user inputs. One is input and the other one is raw_input. You can think of the relation between them as follows
input = eval(raw_input)
Consider the following piece of code to understand this better
>>> dude = "thefourtheye"
>>> input_variable = input("Enter your name: ")
Enter your name: dude
>>> input_variable
'thefourtheye'
input accepts a string from the user and evaluates the string in the current Python context. When I type dude as input, it finds that dude is bound to the value thefourtheye and so the result of evaluation becomes thefourtheye and that gets assigned to input_variable.
If I enter something else which is not there in the current python context, it will fail will the NameError.
>>> input("Enter your name: ")
Enter your name: dummy
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'dummy' is not defined
Security considerations with Python 2.7's input:
Since whatever user types is evaluated, it imposes security issues as well. For example, if you have already loaded os module in your program with import os, and then the user types in
os.remove("/etc/hosts")
this will be evaluated as a function call expression by python and it will be executed. If you are executing Python with elevated privileges, /etc/hosts file will be deleted. See, how dangerous it could be?
To demonstrate this, let's try to execute input function again.
>>> dude = "thefourtheye"
>>> input("Enter your name: ")
Enter your name: input("Enter your name again: ")
Enter your name again: dude
Now, when input("Enter your name: ") is executed, it waits for the user input and the user input is a valid Python function invocation and so that is also invoked. That is why we are seeing Enter your name again: prompt again.
So, you are better off with raw_input function, like this
input_variable = raw_input("Enter your name: ")
If you need to convert the result to some other type, then you can use appropriate functions to convert the string returned by raw_input. For example, to read inputs as integers, use the int function, like shown in this answer.
In python 3.x, there is only one function to get user inputs and that is called input, which is equivalent to Python 2.7's raw_input.
You are running Python 2, not Python 3. For this to work in Python 2, use raw_input.
input_variable = raw_input ("Enter your name: ")
print ("your name is" + input_variable)
Since you are writing for Python 3.x, you'll want to begin your script with:
#!/usr/bin/env python3
If you use:
#!/usr/bin/env python
It will default to Python 2.x. These go on the first line of your script, if there is nothing that starts with #! (aka the shebang).
If your scripts just start with:
#! python
Then you can change it to:
#! python3
Although this shorter formatting is only recognized by a few programs, such as the launcher, so it is not the best choice.
The first two examples are much more widely used and will help ensure your code will work on any machine that has Python installed.
I also encountered this issue with a module that was supposed to be compatible for python 2.7 and 3.7
what i found to fix the issue was importing:
from six.moves import input
this fixed the usability for both interpreters
you can read more about the six library here
You should use raw_input because you are using python-2.7. When you use input() on a variable (for example: s = input('Name: ')), it will execute the command ON the Python environment without saving what you wrote on the variable (s) and create an error if what you wrote is not defined.
raw_input() will save correctly what you wrote on the variable (for example: f = raw_input('Name : ')), and it will not execute it in the Python environment without creating any possible error:
input_variable = raw_input('Enter Your Name : ')
print("Your Name Is : " + (input_variable))
input_variable = input ("Enter your name: ")
print ("your name is" + input_variable)
You have to enter input in either single or double quotes
Ex:'dude' -> correct
dude -> not correct
For python 3 and above
s = raw_input()
it will solve the problem on pycharm IDE
if you are solving on online site exactly hackerrank then use:
s = input()
We are using the following that works both python 2 and python 3
#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Enter your name: "))
There are two ways to fix these issues,
1st is simple without code change that is
run your script by Python3,
if you still want to run on python2 then
after running your python script, when you are entering the input keep in mind
if you want to enter string then just start typing down with "input goes with double-quote" and it will work in python2.7 and
if you want to enter character then use the input with a single quote like 'your input goes here'
if you want to enter number not an issue you simply type the number
2nd way is with code changes
use the below import and run with any version of python
from six.moves import input
Use raw_input() function instead of input() function in your code with any import
sanitise your code with str() function like str(input()) and then assign to any variable
As error implies: name 'dude' is not defined
i.e. for python 'dude' become variable here and it's not having any value of python defined type assignedso only its crying like baby so if we define a 'dude' variable and assign any value and pass to it, it will work but that's not what we want as we don't know what user will enter and moreover we want to capture the user input.
Fact about these method:
input() function: This function takes the value and type of the input you enter as it is without modifying it type. raw_input()
function: This function explicitly converts the input you give into type string,
Note: The vulnerability in input() method lies in the fact that
the variable accessing the value of input can be accessed by anyone
just by using the name of variable or method.
Try using raw_input rather than input if you simply want to read strings.
print("Enter your name: ")
x = raw_input()
print("Hello, "+x)
You could either do:
x = raw_input("enter your name")
print "your name is %s " % x
or:
x = str(input("enter your name"))
print "your name is %s" % x
For anyone else that may run into this issue, turns out that even if you include #!/usr/bin/env python3 at the beginning of your script, the shebang is ignored if the file isn't executable.
To determine whether or not your file is executable:
run ./filename.py from the command line
if you get -bash: ./filename.py: Permission denied, run chmod a+x filename.py
run ./filename.py again
If you've included import sys; print(sys.version) as Kevin suggested, you'll now see that the script is being interpreted by python3
Good contributions the previous ones.
import sys; print(sys.version)
def ingreso(nombre):
print('Hi ', nombre, type(nombre))
def bienvenida(nombre):
print("Hi "+nombre+", bye ")
nombre = raw_input("Enter your name: ")
ingreso(nombre)
bienvenida(nombre)
#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Your name: "))
Enter your name: Joe
('Hi ', 'Joe', <type 'str'>)
Hi Joe, bye
Your name: Joe
Joe
Thanks!
You can change which python you're using with your IDE, if you've already downloaded python 3.x it shouldn't be too hard to switch. But your script works fine on python 3.x, I would just change
print ("your name is" + input_variable)
to
print ("your name is", input_variable)
Because with the comma it prints with a whitespace in between your name is and whatever the user inputted. AND: if you're using 2.7 just use raw_input instead of input.
Here is an input function which is compatible with both Python 2.7 and Python 3+:
(Slightly modified answer by #Hardian) to avoid UnboundLocalError: local variable 'input' referenced before assignment error
def input_compatible(prompt=None):
try:
input_func = raw_input
except NameError:
input_func = input
return input_func(prompt)
Also here is another alternative without a try block:
def input_compatible(prompt=None):
input_func = raw_input if "raw_input" in __builtins__.__dict__ else input
return input_func(prompt)
I want to run command line in python, and capture the output. I can use subprocess.check_output. But it will suppress the output, how can i do it without suppressing the console output?
How about this?
from subprocess import Popen, PIPE
proc = Popen(["/usr/bin/nc", "-l", "9999"], stdout=PIPE)
buffer = []
line = proc.stdout.readline()
while line:
buffer.append(line)
print "LINE", line.strip()
line = proc.stdout.readline()
print "buffer", ''.join(buffer)
Using another terminal send some text
nc localhost 9999
# type something. the text should appear from the python code
Break the nc, and you get the output in buffer as well
I use this command on the Linux terminal to perform a function on a file ./pythonfile.py --count ../textfile.txt
now I use that command on windows on command prompt and it doesn't work.
I use python pythonfile.py --count ./textfile.txt to read and count the text after every white space .
When I press enter it gives the error.
error is : IOError: [Errno 2] NO such file or directory: '--count'
import sys
def cat(filename):
f=open(filename,'rU')
text=f.read()
print text
f.close()
def main():
cat(sys.argv[1])
if __name__=="__main__":
main()
You should get the same error on Linux. You can inspect sys.argv with:
print(sys.argv)
It prints:
['pythonfile.py', '--count', './textfile.txt']
Use sys.argv[2] to get to your file name:
def main():
print(sys.argv)
cat(sys.argv[2])
This should work on Windows too.
I generate xml content from input file using an xml_gen.bat file (I cannot modify it), and I use it like this on Windows cmd to generate xml:
xml_gen --options [inputname] [optional outputname]
I also have a python script xml_parse.py that parses xml input:
import sys
import lxml.etree as ET
def xml_parse(xml_input):
for event, elem in ET.iterparse(xml_input, events=('end', ), tag='TAG'):
# do something
# write parsed content to file
elem.clear()
def main():
xml_parse(sys.stdin)
if __name__ == '__main__':
main()
Both xml_gen and xml_parse.py work when tested separately, i.e., xm_gen can take an input file and generate a correct xml file; xml_parse.py (ran in PyCharm) can take an input xml file from disk and do the parsing correctly.
Since my actual experiment will generate gigabytes of xml from xml_gen, I want to pipe the output of xml_gen directly to the python script to process them.
When I tried:
dir_to_xml_gen\xml_gen --option dir_to_input\input | python xml_parse.py
It produced such error:
Traceback (most recent call last): File "xml_parse.py", line 77, in
main() File "xml_parse.py", line 71, in main xml_parse(sys.stdin) File "xml_parse.py", line 50, in xml_parse for event, elem in ET.iterparse(xml_parse, events=('end', ), tag='TAG'):File "iterparse.pxi", line 208, in lxml.etree.iterparse.next (src\lxml\lxml.etree.c:131498) lxml.etree.XMLSyntaxError: Document is empty, line 2, column 1 ! System error ! 'SPIO_E_END_OF_FILE'
when I tried: dir_to_xml_gen\xml_gen --option dir_to_input\input | python xml_parse.py
it produced similar error: System error 'SPIO_E_END_OF_FILE'
I'm aware of the issues in Cannot redirect output when I run Python script on Windows using just script's name, and followed directions here STDIN/STDOUT Redirection May Not Work If Started from a File Association, but didn't solve my problem. Thank you for your help.