Print new line not working in Python - python

The \n just doesn't seem to work for me when I use it with print. I am using Python 2.7.8. I don't get whats wrong, I think \n with a print should print a new line very straight forwardly.
import sys
import os
import subprocess
from collections import OrderedDict
import xmlrpclib
import hawkey
op_name = sys.argv[1]
pkg_name = sys.argv[2]
# Hawkey Configurations
sack = hawkey.Sack()
path = "/home/thejdeep/test_repo/repodata/%s"
repo = hawkey.Repo("test")
repo.repomd_fn = path % "repomd.xml"
repo.primary_fn = path % "b6f6911f7d9fb63f001388f1ecd0766cec060c1d04c703c6a74969eadc24ec97-primary.xml.gz"
repo.filelists_fn = path % "df5897ed6d3f87f2be4432543edf2f58996e5c9e6a7acee054f9dbfe513df4da-filelists.xml.gz"
sack.load_repo(repo,load_filelists=True)
# Main Function
if __name__ == "__main__":
print "Querying the repository\n"
print "-----------------------\n"
print "Found packages :\n"
print "--------------\n"
q = hawkey.Query(sack)
q = q.filter(name=pkg_name,latest_per_arch=True)[0]
if q:
for pkg in q:
print str(pkg)
else:
print "No packages with name "+pkg_name+" found. Exiting"
sys.exit()
print "--------------------"
print "Performing Dependency Check"
Output is something like this. Basically its printing in the same line :
Querying the repository ----------------------- Found packages : --------------

Using print method automatically add \n at the end of the line so its not necessary put \n at the end of each line.

Related

How can i get the user input as argument for delete function in my code while executing program from CLI

This program runs stand alone perfectly when executed, but when this script gets called from another script, it gives 'EOFError: EOF when reading a line'
Below is my code:
'''
#!/usr/bin/python
import pdb
#pdb.set_trace()
from lxml import etree as ET
import argparse
import os
import sys
from colors import *
filename = "/appl/OMS/Build_Details/build_details.xml"
parser = ET.XMLParser(remove_blank_text=True)
tree = ET.parse(filename, parser)
root = tree.getroot()
parser = argparse.ArgumentParser()
parser.add_argument("r", help="Provide Release Number")
parser.add_argument("b", help="Provide Build number")
parser.add_argument("oms", help="Provide OMS Storage Name")
parser.add_argument("pc", help="Provide PC version")
parser.add_argument("omni", help="Provide OMNI Storage Name")
args = parser.parse_args()
def display():
sys.stdout.write(RESET)
print "Displaying all existing releases in Build XML"
for elem in root.iter("Release"):
sys.stdout.write(GREEN)
print int(elem.attrib['number']),
print " "
def add_details():
counter=0
for elem in root.iter("Release"):
#print int(elem.attrib['number']),int(args.r)
if int(elem.attrib['number']) == int(args.r):
sys.stdout.write(YELLOW)
print "Release found!!",
counter=counter+1
break
if counter == 1:
for a in elem.iter('Build'):
#print a.attrib['number']
if int(a.attrib['number']) == int(args.b):
print "Build already exists"
break
else:
#Take backup od existing build xml
os.system('cp /appl/OMS/Build_Details/build_details.xml /appl/OMS/Build_Details/Backup/build_details.xml_$(date +"%Y%m%d-%H%M%S")')
#Create new OMS element
build_elem = ET.Element("Build", {"number": args.b})
oms_elem = ET.Element("OMS")
build_path_elem = ET.Element("Build_path")
build_path_elem.text = args.oms
pc_version_elem = ET.Element("Pc_version")
pc_version_elem.text = args.pc
oms_elem.append(build_path_elem)
oms_elem.append(pc_version_elem)
# OMNI element
omni_elem = ET.Element("OMNI")
build_path_omni_elem = ET.Element("Build_path")
build_path_omni_elem.text = args.omni
omni_elem.append(build_path_omni_elem)
build_elem.append(oms_elem)
build_elem.append(omni_elem)
elem.append(build_elem)
# Write to file
tree.write("/appl/OMS/Build_Details/build_details.xml",pretty_print=True) # After adding the new element
print "Adding build details"
else:
#Take backup of existing build xml
os.system('cp /appl/OMS/Build_Details/build_details.xml /appl/OMS/Build_Details/Backup/build_details.xml_$(date +"%Y%m%d-%H%M%S")')
# Create new Release Element
Release = ET.SubElement(root, "Release",number=args.r)
#Build elementq
Build = ET.SubElement(Release, "Build", number=args.b)
OMS=ET.SubElement(Build,"OMS")
ET.SubElement(OMS,"Build_path").text =args.oms
ET.SubElement(OMS,"Pc_version").text =args.pc
OMNI=ET.SubElement(Build,"OMNI")
ET.SubElement(OMNI,"Build_path").text =args.omni
tree.write("/appl/OMS/Build_Details/build_details.xml",pretty_print=True) # After adding the new element
sys.stdout.write(YELLOW)
print "Release details added"
def delete():
sys.stdout.write(RESET)
release_number = int(input("Enter the release number you want to delete or else enter 0\n"))
for elem in root.iter("Release"):
if int(elem.attrib['number']) == int(release_number):
sys.stdout.write(YELLOW)
print "Release found"
root.remove(elem)
#Take backup od existing build xml
os.system('cp /appl/OMS/Build_Details/build_details.xml /appl/OMS/Build_Details/Backup/build_details.xml_$(date +"%Y%m%d-%H%M%S")')
tree.write("/appl/OMS/Build_Details/build_details.xml",pretty_print=True)
print "Delete complete"
def main():
#print "Calling add details"
add_details()
#print "calling display"
print "\n"
display()
#print "Calling delete "
print "\n"
delete()
#print "calling second display"
print "\n"
display()
sys.stdout.write(RESET)
main()
'''
Please let me know how can i pass the runtime input i am taking for my delete function as an argument like others.
I an new to python and experimenting with the language

I am trying to write data into file

When I run then i get error.why print man gave error and also os.getwd() also give error.But when i comment that then there is no error.code works according to expectation
from __future__ import print_function;
import os
man=[]
other = []
print os.getcwd()
try:
data = open("sketch.txt")
for each_line in data:
try:
(role,line_spoken) = each_line.split(':',1)
line_spoken = line_spoken.strip()
if role=='Man':
man.append(line_spoken)
elif role =='Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print ("The Data File is Missing")
print man
print other
try:
man_file = open('man_data.txt','w')
other_file = open('other_data.txt','w')
print (man,file = man_file)
print (other,file = other_file)
other_file.close()
man_file.close()
except IOError:
pass
You should call print as function, because you import print_function:
from __future__ import print_function
print("Hello World")
As far as I see the following.
1) In the first line there is a ';' that could be removed.
2) the second line 'import...' and the rest to the bottom have tabs that should be removed. These lines should be in the same col that line 1 ('from ...')
3) when you use 'print' (as other people are saying) you should use '(' & ')'.
4) for coherence you should get used to follow the same approach in all your code (good practiceS), if there are no spaces between function names and parameters (i.e. line 7: data = open("sketch...) then go on with them. The same for strings, the code compile, but it is better if you use ' or " not mix them along the code.
looking forward to help!

Getting a tracklist from MusicBrainz

I am trying to learn Python, and thought I'd learn by writing something I'd actually use. SO I'm trying to write a little script to rip some music CDs.
I am using the musicbrainzngs package. I would like to get the tracklist of the CD. My code currently:
#! /usr/bin/env python
import argparse
import musicbrainzngs
import discid
musicbrainzngs.set_useragent("Audacious", "0.1", "https://github.com/jonnybarnes/audacious")
parser = argparse.ArgumentParser()
parser.add_argument("--cdrom", help="provide the source of the cd", default="/dev/cdrom")
args = parser.parse_args()
device = args.cdrom
print("device: %s" % device)
disc = discid.read(device)
print("id: %s" % disc.id)
try:
result = musicbrainzngs.get_releases_by_discid(disc.id, includes=["artists"])
except musicbrainzngs.ResponseError:
print("disc not found or bad response")
else:
if result.get("disc"):
print("artist:\t%s" %
result["disc"]["release-list"][0]["artist-credit-phrase"])
print("title:\t%s" % result["disc"]["release-list"][0]["title"])
elif result.get("cdstub"):
print("artist:\t" % result["cdstub"]["artist"])
print("title:\t" % result["cdstub"]["title"])
How can I get the tracklist, looking at the full results returned there is a track-list property but regardless of what CD I try the result is always empty
Getting releases by discid is a lookup and its "'inc=' arguments supported are identical to a lookup request for a release" which are listed earlier on that page. To get a non-empty tracklist you simply need to add the "recordings" include:
result = musicbrainzngs.get_releases_by_discid(disc.id, includes=["artists", "recordings"])
This is an example script for getting the tracklist for an album using musicbrainzngs
#!/usr/bin/python3
from __future__ import print_function
from __future__ import unicode_literals
import musicbrainzngs
import sys
musicbrainzngs.set_useragent(
"python-musicbrainzngs-example",
"0.1",
"https://github.com/alastair/python-musicbrainzngs/",
)
def get_tracklist(artist, album):
result = musicbrainzngs.search_releases(artist=artist, release=album, limit=1)
id = result["release-list"][0]["id"]
#### get tracklist
new_result = musicbrainzngs.get_release_by_id(id, includes=["recordings"])
t = (new_result["release"]["medium-list"][0]["track-list"])
for x in range(len(t)):
line = (t[x])
print(f'{line["number"]}. {line["recording"]["title"]}')
if __name__ == '__main__':
### get first release
if len(sys.argv) > 1:
artist, album = [sys.argv[1], sys.argv[2]]
get_tracklist(artist, album)
else:
artist = input("Artist: ")
album = input("Album: ")
if not artist == "" and not album == "":
get_tracklist(artist, album)
else:
print("Artist or Album missing")
Usage:
python3 album_get_tracklist.py "rolling stones" "beggars banquet"
or
python3 album_get_tracklist.py
it will ask for Artist and Album

Compare RPM Packages using Python

I'm trying to compare a csv file containing required Linux packages with the current installed packages. The comparison should output any packages not installed or newer than the current installed packages.
The problem is that I'm unable to loop through the list of installed packages and show all hits, for instance packages with the same name and version, but different architecture should be shown twice(for instance compat-libstdc++-33), but I only getting the first hit with the script below.
#!/usr/bin/python
import rpm
import csv
import sys
import os
'''
Script to check installed rpms against a csv file containing the package name and version similar to the list below:
atk,1.12.2
libart_lgpl,2.3
info,4.9
libsepol,1.15.2
libusb,0.1.12
libfontenc,1.4.2
'''
if len(sys.argv) !=2:
print ''
print 'Usage: ', sys.argv[0], '/path/to/csv_input_file'
print ''
sys.exit(1)
if not os.path.isfile(sys.argv[1]):
print ''
print sys.argv[1], 'not found!'
print ''
sys.exit(1)
else:
input_csv = sys.argv[1]
pkgRequired = csv.reader(open(input_csv),delimiter=',')
pkgInstalledName = []
pkgInstalledVersion = []
pkgInstalledArch = []
ts = rpm.TransactionSet()
mi = ts.dbMatch()
for h in mi:
pkgInstalledName.append((h['name']))
pkgInstalledVersion.append((h['version']))
pkgInstalledArch.append((h['arch']))
for row in pkgRequired:
pkgRequiredName = row[0]
pkgRequiredVersion = row[1]
#pkgRequiredArch = row[2]
if pkgRequiredName in pkgInstalledName:
if pkgInstalledVersion[pkgInstalledName.index(pkgRequiredName)] >= pkgRequiredVersion:
pass
else:
print '\nInstalled: ',pkgInstalledName[pkgInstalledName.index(pkgRequiredName)], pkgInstalledVersion[pkgInstalledName.index(pkgRequiredName)], pkgInstalledArch[pkgInstalledName.index(pkgRequiredName)], ' \nRequired: ', ' ', pkgRequiredName,pkgRequiredVersion
Assuming that there's no problem with the way that you're reading the list of installed packages (I'm not familiar with the rpm module), then your only problem is with using the index() function. This function return the first occurrence of an item with the specified value - and it isn't what you want.
A correct implementation (which is also much more efficient) would be:
installedPackages = {} #create a hash table, mapping package names to LISTS of installed package versions and architectures
for h in mi:
l = installedPackages.get(h['name'], list()) #return either the existing list, or a new one if this is the first time that the name appears.
l.append( (h['version'], h['arch']) )
...
if requiredPackageName in installedPackages:
for ver, arch in installedPackages[requiredPackageName]: print ...
This is what I ended up doing to get this working. The script currently is not checking for the architecture of required packages, but at least it shows the arch installed. The script works (as far as I know) but can be improved as its my first at python :)
#!/usr/bin/python
import rpm
import csv
import sys
import os
'''
Script to check installed rpms against a csv file containing the package name and version similar to the list below:
atk,1.12.2
libart_lgpl,2.3
info,4.9
libsepol,1.15.2
libusb,0.1.12
libfontenc,1.4.2
'''
#silverbullet - 20120301
if len(sys.argv) !=2:
print ''
print 'Usage: ', sys.argv[0], '/path/to/csv_input_file'
print ''
sys.exit(1)
if not os.path.isfile(sys.argv[1]):
print ''
print sys.argv[1], 'not found!'
print ''
sys.exit(1)
else:
input_csv = sys.argv[1]
pkgRequired = csv.reader(open(input_csv),delimiter=',')
pkgInstalledName = []
pkgInstalledVersion = []
pkgInstalledArch = []
ts = rpm.TransactionSet()
mi = ts.dbMatch()
for h in mi:
pkgInstalledName.append((h['name']))
pkgInstalledVersion.append((h['version']))
pkgInstalledArch.append((h['arch']))
for row in pkgRequired:
try:
pkgRequiredName = row[0]
pkgRequiredVersion = row[1]
#pkgRequiredArch = row[2] - This is not implemented yet, ie, script will ignore architecture in csv input file
except:
print "Unexpected Error. Check if input is csv format with no blank lines. "#, sys.exc_info()[1]
break
else:
for pos, pkg in enumerate(pkgInstalledName):
if pkg == pkgRequiredName:
if pkgInstalledVersion[pos] >= pkgRequiredVersion:
pass
else:
print '\nInstalled:', pkgInstalledName[pos], pkgInstalledVersion[pos], pkgInstalledArch[pos], '\nRequired: ', pkg, pkgRequiredVersion

IOError opening an existing file with Python

Running the following code:
import os
import datetime
import ftplib
currdate = datetime.datetime.now()
formatdate = currdate.strftime("%m-%d-%Y %H%M")
def log():
fqn = os.uname()[1]
ext_ip = urllib2.urlopen('http://whatismyip.org').read()
log = open ('/Users/admin/Documents/locatelog.txt','w')
log.write(str("Asset: %s " % fqn))
log.write(str("Checking in from IP#: %s" % ext_ip))
smush = str(fqn +' # ' + formatdate)
os.rename('/Users/admin/Documents/locatelog.txt','/Users/admin/Documents/%s.txt' % smush )
s = ftplib.FTP('10.7.1.71','username','password')
f = open('/Users/admin/Documents/%s.txt' % smush,'r')
s.storbinary("STOR /Users/admin/Documents/%s.txt" % smush,f)
Generates the following error:
ftplib.error_perm: 550 /Users/admin/Documents/678538.local # 02-24-2010 1301.txt: No such file or directory
I have a feeling something is amiss in this line :
s.storbinary("STOR /Users/admin/Documents/%s.txt" % smush,f)
678538 is the host I am testing on...using Mac OS X 10.5 and Python 2.5.1
Shouldn't it bef = open('/Users/admin/Documents/%s.txt' % smush,'r') ? notice the / in front of Users
If you dont put the first /, the script will think the path to the file is relative to the current directory (where the script is run from)
Edit:
I m not too familiar with Python (I wish) but shouldnt it be:
s.storbinary('STOR /Users/admin/Documents/%s.txt' % smush,f) ?
In your example, Python will treat your string as literal and you want to interpolate the value of smush with %s
Edit 2:
Does the directory /Users/admin/Documents/ exist on your server? If not, I think you will have to create them before copying anything. (Since the error message is about some files/folders missing).
You can create them yourself first. Run your script. If the file is copied successfully, then you can add the creation of the directories from within your script.
remove all spaces from file name .eg in smush = str(fqn +' # ' + formatdate), you are putting a space in front of and after "#". you path looks like
/Users/admin/Documents/something # something
and when you pass it to ftplib, it may have problem. another way is to try putting quotes, eg
s.storbinary("STOR '/Users/admin/Documents/%s.txt'" % smush,f)
Edit:
This version works: Problem was that I was writing to buffer, and not to file.
import os
import urllib2
import datetime
import ftplib
currdate = datetime.datetime.now()
formatdate = currdate.strftime("%m-%d-%Y-%H%M")
def log():
fqn = os.uname()[1]
ext_ip = urllib2.urlopen('http://whatismyip.org').read()
smush = str(fqn + formatdate)
s = ftplib.FTP('10.7.1.71','username','password')
f = open('/Users/admin/Documents/%s.txt' % smush,'w')
f.write(str("Asset: %s " % fqn))
f.write('\n')
f.write(str("Checking in from IP#: %s" % ext_ip))
f.write('\n')
f.write(str("On: %s" % formatdate))
f.close
f = open('/Users/admin/Documents/%s.txt' % smush,'rb')
s.storbinary('STOR %s.txt' % smush , f)
s.close
f.close

Categories

Resources