I'm searching a string into 2 websites.
Each website have the same string, now the main problem is:
s = "name:'(.*)',"
WebType = re.findall(s, html1)
for name in WebType:
if 'RoundCube' or 'SquirrelMail' in name:
print host + "--> " + name
So basically, I think that the results repeat depending on loop results.
The results are:
https://website1.com--> Roundcube
https://website1.com--> SquirrelMail
https://website2.com--> Roundcube
https://website2.com--> SquirrelMail
How can I make the results to be:
https://website1.com--> RoundCube, SquirrelMail
https://website2.com--> Roundcube, SquirrelMail
dursk's solution above should have worked. However, a longer solution is:
s = "name:'(.*)',"
WebType = re.findall(s, html1)
results = []
for name in WebType:
if 'RoundCube' or 'SquirrelMail' in name:
results.append(name)
print host + "--> " + ', '.join(results)
Try this code:
import random
hosts = ['https://website1.com', 'https://website2.com']
WebList = ['RoundCube', 'SquirrelMail'] + ['webtype_{}'.format(x) for x in range(2)]
WebType = WebList[random.randint(0, len(WebList)):]
name_list = ['RoundCube', 'SquirrelMail']
for host in hosts:
name = filter(set(WebType).__contains__, name_list)
if len(name):
print host + "--> " + str(name).lstrip('[').rstrip(']').replace('\'', '')
I created WebList for testing purposes.
In your code, you will not need to import random unless you want to test what's here.
It outputs:
https://website1.com--> RoundCube, SquirrelMail
https://website2.com--> RoundCube, SquirrelMail
It also outputs:
https://website1.com--> SquirrelMail
https://website2.com--> SquirrelMail
You might need to adjust it to your needs.
Related
I am trying to automate some of the manual tasks using python3 and I am not sure how to print a variable. I know I can use print(f"https://{ip1}", but I am trying to solve this problem using "for loops"
Here is the part of the code.
......
def hostFile():
hostConf = (projdateprojname[9:])
print("\n\tEnter legacy host IP")
ip1 = input(prompt)
print("\n\tEnter legacy guest IP")
ip2 = input(prompt)
print("\n\tEnter legacy host IP")
ip3 = input(prompt)
print("\n\tEnter legacy guest IP")
ip4 = input(prompt)
print(f"\n[{hostConf}-1]")
print(f"{ip1}")
print(f"{ip2}")
print(f"{ip3}")
print(f"{ip4}")
for i in range(1, 5):
listofurl = ("ip" + str(i))
print(f"https://{listofurl}")
Script output for the last part:
https://ip1
https://ip2
https://ip3
https://ip4
I am expecting to see, for example
https://10.1.1.199
https://10.1.1.200
https://10.1.1.201
https://10.1.1.202
I see what you were trying to do, just one adjustment change
listofurl = ("ip" + str(i))
to
listofurl = (locals()["ip" + str(i)])
locals() return a dictionary{} of variables in the current scope, ["ip" + str(i)] gets translated to ["ip<i>"] wherei changes value during each phase of the loop
I am currently using python 2.7 and will need to ping windows and linux.
I want to create a function that will return the IP address from a ping within a python script. I currently have this function
def ping(host):
"""
Returns True if host responds to a ping request
"""
import subprocess, platform
# Ping parameters as function of OS
ping_str = "-n 1" if platform.system().lower()=="windows" else "-c 1"
args = "ping " + " " + ping_str + " " + host
need_sh = False if platform.system().lower()=="windows" else True
# Ping
return subprocess.call(args, shell=need_sh) == 0
Right now it just returns true or false but is there a way I can run ping(google.com) and have it return 216.58.217.206. I have a list of servers and IPs and I need to make sure that the IP addresses match the FQDN.
You can use the socket to get the IP of the host.
import socket
print(socket.gethostbyname('www.example.com'))
Not sure how no-one has tried this method yet (for windows anyways)!
Use a WMI query of W32_PingStatus
With this method we return an object full of goodies
import wmi
# new WMI object
c = wmi.WMI()
# here is where the ping actually is triggered
x = c.Win32_PingStatus(Address='google.com')
# how big is this thing? - 1 element
print 'length x: ' ,len(x)
#lets look at the object 'WMI Object:\n'
print x
#print out the whole returned object
# only x[0] element has values in it
print '\nPrint Whole Object - can directly reference the field names:\n'
for i in x:
print i
#just a single field in the object - Method 1
print 'Method 1 ( i is actually x[0] ) :'
for i in x:
print 'Response:\t', i.ResponseTime, 'ms'
print 'TTL:\t', i.TimeToLive
#or better yet directly access the field you want
print '\npinged ', x[0].ProtocolAddress, ' and got reply in ', x[0].ResponseTime, 'ms'
Screenshot of output:
I am using the following code to process a list of images that is found in my scene, before the gathered information, namely the tifPath and texPath is used in another function.
However, example in my scene, there are 3 textures, and hence I should be seeing 3 sets of tifPath and texPath but I am only seeing 1 of them., whereas if I am running to check surShaderOut or surShaderTex I am able to see all the 3 textures info.
For example, the 3 textures file path is as follows (in the surShaderTex): /user_data/testShader/textureTGA_01.tga, /user_data/testShader/textureTGA_02.tga, /user_data/testShader/textureTGA_03.tga
I guess what I am trying to say is that why in my for statement, it is able to print out all the 3 results and yet anything bypass that, it is only printing out a single result.
Any advices?
surShader = cmds.ls(type = 'surfaceShader')
for con in surShader:
surShaderOut = cmds.listConnections('%s.outColor' % con)
surShaderTex = cmds.getAttr("%s.fileTextureName" % surShaderOut[0])
path = os.path.dirname(surShaderTex)
f = surShaderTex.split("/")[-1]
tifName = os.path.splitext(f)[0] + ".tif"
texName = os.path.splitext(f)[0] + ".tex"
tifPath = os.path.join(path, tifName)
texPath = os.path.join(path, texName)
convertText(surShaderTex, tifPath, texPath)
Only two lines are part of your for loop. The rest only execute once.
So first this runs:
surShader = cmds.ls(type = 'surfaceShader')
for con in surShader:
surShaderOut = cmds.listConnections('%s.outColor' % con)
surShaderTex = cmds.getAttr("%s.fileTextureName" % surShaderOut[0])
Then after that loop, with only one surShader, one surShaderOut, and one surShaderTex, the following is executed once:
path = os.path.dirname(surShaderTex)
f = surShaderTex.split("/")[-1]
tifName = os.path.splitext(f)[0] + ".tif"
texName = os.path.splitext(f)[0] + ".tex"
tifPath = os.path.join(path, tifName)
texPath = os.path.join(path, texName)
Indent that the same as the lines above it, and it'll be run for each element of surShader instead of only once.
I am looking to figure out both the current Battery Capacity and the Design Capacity.
So far what I could get to work is using the Win32_Battery() class which doesn't give all the information I need (at least not on my system). I used the pure-python wmi library for that.
On the other hand I found this which works In Python, how can I detect whether the computer is on battery power?, but unfortunately it doesn't provide any information on Capacity neither.
The Battery Information structure and the Battery Status structure seem perfect for this. Now I know that I have to use the DeviceIoControl function to do so and I found this C++ code that explains it a little.
I would prefer something that simply uses ctypes and not the python win32api provided by pywin32.
If you have an idea how to do this in python please let me know!
Thanks in advance.
The most reliable way to retrieve this information is by using GetSystemPowerStatus instead of WMI. psutil exposes this information under Linux, Windows and FreeBSD:
>>> import psutil
>>>
>>> def secs2hours(secs):
... mm, ss = divmod(secs, 60)
... hh, mm = divmod(mm, 60)
... return "%d:%02d:%02d" % (hh, mm, ss)
...
>>> battery = psutil.sensors_battery()
>>> battery
sbattery(percent=93, secsleft=16628, power_plugged=False)
>>> print("charge = %s%%, time left = %s" % (battery.percent, secs2hours(battery.secsleft)))
charge = 93%, time left = 4:37:08
The relevant commit is here.
Tim Golden's excellent wmi module will, I believe, give you everything you want. You'll just have to do several queries to get everything:
import wmi
c = wmi.WMI()
t = wmi.WMI(moniker = "//./root/wmi")
batts1 = c.CIM_Battery(Caption = 'Portable Battery')
for i, b in enumerate(batts1):
print 'Battery %d Design Capacity: %d mWh' % (i, b.DesignCapacity or 0)
batts = t.ExecQuery('Select * from BatteryFullChargedCapacity')
for i, b in enumerate(batts):
print ('Battery %d Fully Charged Capacity: %d mWh' %
(i, b.FullChargedCapacity))
batts = t.ExecQuery('Select * from BatteryStatus where Voltage > 0')
for i, b in enumerate(batts):
print '\nBattery %d ***************' % i
print 'Tag: ' + str(b.Tag)
print 'Name: ' + b.InstanceName
print 'PowerOnline: ' + str(b.PowerOnline)
print 'Discharging: ' + str(b.Discharging)
print 'Charging: ' + str(b.Charging)
print 'Voltage: ' + str(b.Voltage)
print 'DischargeRate: ' + str(b.DischargeRate)
print 'ChargeRate: ' + str(b.ChargeRate)
print 'RemainingCapacity: ' + str(b.RemainingCapacity)
print 'Active: ' + str(b.Active)
print 'Critical: ' + str(b.Critical)
This is certainly not cross-platform, and it requires a 3rd party resource, but it does work very well.
import psutil
battery = psutil.sensors_battery()
plugged = battery.power_plugged
percent = str(battery.percent)
The variable percent will have the battery percent.
I have written a small piece of code using python to notify when the battery is fully charged
https://github.com/Mitzzzzz/Battery-Full-Indicator
Kindly check!!
**Checking the battery percentage in python can be done using the psutil module as
follows **
# Installing the psutil module
from pip._internal import main
main(["install", "psutil"])
import psutil
battery = psutil.sensors_battery();
# checking if the charger is plugged
if battery.power_plugged:
print("Charging: ", battery.percent)
else:
print("Not Charging", battery.percent ,"%");
print( "Discharge time ", int(battery.secsleft)," sec_lft")
The Most Easiest Form to Know the Battery With Python is using Psutil Module...
import psutil #pip install psutil
battery_detecting = psutil.sensors_battery()
plugged = battery_detecting.power_plugged
percent_battery = str(battery_detecting.percent)
plugged = "Plugged In" if plugged else "Not Plugged In"
print(percent_battery+'% | '+plugged)
Try This Code
import psutil
import time
battery = psutil.sensors_battery()
while True:
print("Battery percentage : ", battery.percent)
print("Power plugged in : ", battery.power_plugged)
if battery.percent < 35 and battery.power_plugged == False:
print("Your battry is low")
time.sleep(5)
But this code will run continously until it get's interrupted
If you are talking about Full Charge Capacity of a battery try this:
I AM USING POWERSHELL NONINTERACTIVE SHELL TO USE THIS COMMAND. THIS IS ONE OF THE EASIEST WAYS TO KNOW BATTERY INFO.
systeminfo = subprocess.run(["Powershell", "-NonInteractive", "-Command", "Get-WmiObject", "-Namespace", "'root\wmi'", "-Query", "'select FullChargedCapacity from BatteryFullChargedCapacity'"], capture_output=True).stdout.decode().strip()
print(systeminfo[292:-21])
NOTE: THIS ONLY WORKS ON WINDOWS
I'm having some issues with the EC2 bit of Boto (Boto v2.8.0, Python v2.6.7).
The first command returns a list of S3 Buckets - all good! The second command to get a list of EC2 instances blows up with a 403 with "Query-string authentication requires the Signature, Expires and AWSAccessKeyId parameters"
s3_conn = S3Connection(AWSAccessKeyId, AWSSecretKey)
print s3_conn.get_all_buckets()
ec2_conn = EC2Connection(AWSAccessKeyId, AWSSecretKey)
print ec2_conn.get_all_instances()
Also, my credentials are all good (Full admin) - I tested them using the Ruby aws-sdk, both EC2 and S3 work fine.
I also noticed that the host attribute in the ec2_conn object is s3-eu-west-1.amazonaws.com, "s3"...? Surely thats wrong? I've tried retro fixing it to the correct endpoint but no luck.
Any help would be great appreciate
Thanks
Here's some working code I use to list all my instances across potentially multiple regions.
Its doing a lot more than you need, but maybe you can pare it down to what you want.
#!/usr/bin/python
import boto
import boto.ec2
import sys
class ansi_color:
red = '\033[31m'
green = '\033[32m'
reset = '\033[0m'
grey = '\033[1;30m'
def name(i):
if 'Name' in i.tags:
n = i.tags['Name']
else:
n = '???'
n = n.ljust(16)[:16]
if i.state == 'running':
n = ansi_color.green + n + ansi_color.reset
else:
n = ansi_color.red + n + ansi_color.reset
return n
def pub_dns( i ):
return i.public_dns_name.rjust(43)
def pri_dns( i ):
return i.private_dns_name.rjust(43)
def print_instance( i ):
print ' ' + name(i) + '| ' + pub_dns(i) + ' ' + pri_dns(i)
regions = sys.argv[1:]
if len(regions)==0:
regions=['us-east-1']
if len(regions)==1 and regions[0]=="all":
rr = boto.ec2.regions()
else:
rr = [ boto.ec2.get_region(x) for x in regions ]
for reg in rr:
print "========"
print reg.name
print "========"
conn = reg.connect()
reservations = conn.get_all_instances()
for r in reservations:
# print ansi_color.grey + str(r) + ansi_color.reset
for i in r.instances:
print_instance(i)
There is the connect_to_region command:
import boto.ec2
connection = boto.ec2.connect_to_region('eu-west-1', aws_access_key_id=AWSAccessKeyId,
aws_secret_access_key=AWSSecretKey)
The Boto tutorial gives another way. That method would basically work like this:
import boto.ec2
for region in boto.ec2.regions():
if region.name == 'my-favorite-region':
connection = region.connect()
break
This has not been working on older versions of Boto.
Do you have your IAM credentials in order? The given access key should have rights for EC2. If you're not sure, you can add the policy AmazonEC2FullAccess to test, and later tune this down.