Indentation error while importing python file in Juypter Notebook - python-3.x

I am running simple code mentioned below, but getting indentation error. I am using Python 3.x and Juypter notebook. Help will be appreciated.
import os
import sys
sys.path.insert(0, os.path.abspath('C:\dir python util'))
import h
h.my_first_function()
In file h.py, which is in drive c:\dir python util contents are below:
def my_first_function():
print ("my first program of python")
Error I am getting:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3331, in run_code exec(code_obj, self.user_global_ns, self.user_ns)
File "", line 5, in import h
File "C:\dir python util\h.py", line 2 print ("my first program of python") ^ IndentationError: expected an indented block

File "C:\dir python util\h.py", line 2 print ("my first program of python") ^ IndentationError: expected an indented block
Error indicates that it is simple indentation error. You need to maintain the appropriate indentation in the code.
With corrected indentation, it'll be as follows:
def my_first_function():
print ("my first program of python")
So print statement needs to have 4 spaces rather than one.
Suggest you to go through this document to get idea about Python's indentation rules, if you don't know that already.

Related

Python3 EOFError: EOF when reading a line (Windows)

I am trying to take input() from keyboard but EOFError is received.
Does anyone know how to solve this issue?
test.py
import sys
if sys.stdin.isatty():
print("keyboard input is working")
else:
print("keyboard input is not working")
# read all input from stdin
data = sys.stdin.read()
print(data)
r = input("Enter something here:")
print(r)
Now, create a dummy text file and pass it to python
#dummy.txt
dummy text goes here.
I then called the python script on Windows using this command:
C:\> test.py < dummy.txt
This is the error I received:
keyboard input is not working
dummy text goes here.
Enter something here:Traceback (most recent call last):
File "C:\test.py", line 11, in <module>
r = input("Enter something here:")
EOFError: EOF when reading a line
C:\>
I kind of know how to solve this issue in Linux by open a file descriptor on /dev/tty and pass it back to sys.stdin but how do I archive this on Windows?
I notice function msvcrt.getch() could work, but there should be a better solution that I can utilize input() function for cross-platform compat.
Please help, anyone!

Pleas help, im not sure whats wrong with the two lines of code

I know this is a super super simple thing but dont know why im getting this error. Im just trying to ask for a name and then execute a print command with the input.
name = input("whats your name?:")
print("hello,", name,"!")
whats your name?:Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
Unknown Error.
Use raw_input() inplace of input()
Please find the modifications
name = raw_input("whats your name?:")
print("hello,", name,"!")

python3: how can I paste code directly into console that calls a function instead of having to load a .py file?

In a python3 console I just want to copy and paste code directly into the console without loading a .py file but I get an error, probably because it's executing only one line at a time?
>>> def k():
... print("Hi")
... k()
File "<stdin>", line 3
k()
^
SyntaxError: invalid syntax
>>>
How can I run multi-line python code by just copying and pasting what I've written, into console instead of loading a .py file? I realize people will say it's stupid to do this, but hypothetically if it weren't stupid to do this, what's the easiest way to do it?
your problem is this:
you have to paste the def k(): after the prompt >>> then paste your function code one line at a time after ... (with indents) then at the end of your function definition add an empty line (no indent) then you will get the >>> prompt again where you paste your function call k() .
this was what I got
>>> def k():
... print("hi")
...
>>> k()
hi
>>>

re.split() works in the interpreter, but, fails on script execution. Python 3

I am having a strange issue. I am trying to write a script to automate NFS mounts and it seems that it is failing on a re.split. I would like to use any number of spaces to delimit the strings, but, for some reason when I run the script it fails. I am generate the following error when I run my script.
basilius#HomeComing:~/PycharmProjects/pythonProject1$ sudo python3 mount_py3.py lin
file.txt rw,noac,suid
Enter the name of the default group: basilius
Enter the default group name: basilius
Traceback (most recent call last):
File "mount_py3.py", line 146, in <module>
main()
File "mount_py3.py", line 125, in main
export, mount_point = re.split(' +', line)
ValueError: not enough values to unpack (expected 2, got 1)
for the following code.
inp_file = open(args.filein, 'r')
for line in inp_file.readline():
export, mount_point = re.split(' +', line)
I use argparse to pass the name of the script, as a string, to the script. It is not being opened by argparse.
When I directly invoke the interpreter it works fine. See below.
basilius#HomeComing:~/PycharmProjects/pythonProject1$ python3
Python 3.6.9 (default, Apr 18 2020, 01:56:04)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> inp_file = open('file.txt', 'r')
>>> line = inp_file.readline()
>>> print(line)
server:/opt/website /srv/program
>>> export, mount_point = re.split(' +', line)
>>> print(export, mount_point)
server:/opt/website /srv/program
>>>
When I do just a straght readlines() on the file it returns everything in the correct format.
It is a straght text file for the export and mount_point for fstab entry. I am not sure why I am getting different results. Could someone assit? I have been pounding the internet for a couple of days now.
The issue is with your loop, where you write for line in inp_file.readline():. This reads a single line from the file, and loops over the characters in the string, assigning each one to line in turn.
You probably want for line in inp_file:, which loops over the lines in the file one at a time. You could also call readlines() (with an "s" on the end) on the file, which does the same thing but uses more memory.
Or, I suppose, if you only care about the first line of the file, you could just do line = inp_file.readline() without the for loop.
Unrelated to your issue, it's a probably good idea to use a with statement to handle the opening and closing of your file: with open(args.filein, 'r') as inp_file:, followed by the rest of the code that uses it indented by one level.

Python: NameError from calling a file from the commandline arguments

For an assignment I'm supposed to have to have a line to open a file that is passed as an argument in the commandline, I keep getting
Traceback (most recent call last):
File "execute.py", line 1, in <module>
program=open(programfilename, "r")
NameError: name 'programfilename' is not defined
My code to this point is program=open(programfilename, "r"). I'm not quiet sure what is wrong. It is the first line in my program. Execute.py is the name of my code.
You need to set the programfilename variable to the name/path of the file on a previous line. Alternatively, you could put the filename in quotes instead.
It is the first line in my program
Well there's your problem. You are using programfilename without having defined it first.
Try something like
import sys
programfilename = sys.argv[0] # argument you passed into your program.
program=open(programfilename, "r")
I am not sure what exactly you are trying to.
If you want to call a file using command line, the code can be like this
import sys
with open(sys.argv[1], 'r') as f:
print(f.read())
Run like this
python3 execute.py programfilename
If you want your program to get printed on the console, the code can be like this
import sys
with open(sys.argv[0], 'r') as f:
print(f.read())
This will print the code on the console.
Run like this
python3 execute.py

Resources