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.