Run shell commands from python and string concatenation - python

I am trying to adjust the "post to dropbox" services for Snow loepard (http://dl.dropbox.com/u/1144075/Post%20to%20Dropbox.zip).
I dont want the public URL, but a shortened one from goo.gl
Therefor I am using these shell commands:
curl -s --data-urlencode "url=http://link.com" http://googl/action/shorten | grep "googl" | awk -F\" '{print $(NF-1)}' | awk 'BEGIN { FS = "=" } ; { print $2}' | pbcopy
Now the python script does this to copy a dropbox URL for all the files it just copies in the public folder to the clipboard:
pasteURLs = []
for file in copied_files: # for all elements in our list
components = file.split(os.sep) # seperate the path
local_dir = os.sep.join(components[5:]) # cut off the beginning
local_dir = urllib.quote(local_dir) # convert it to a URL (' ' -> '%20', etc.)
#construct the URL
finalURL = 'http://dl.dropbox.com/u/%s/%s' % ( dropbox_id, local_dir )
pasteURLs.append(finalURL) # add the current URL to the string
copy_string = "\n".join(pasteURLs)
os.system( "echo '%s' | pbcopy" % (copy_string) ) # put the string into clipboard
I have to admit I dont know anything about python, but from what it looks like, I need to change the last two lines with this:
shortURL = []
for thisURL in pasteURLs:
shortURL = os.system( curl -s --data-urlencode "url=http://link.com" http://googl/action/shorten | grep "goo.gl" | awk -F\" '{print $(NF-1)}' | awk 'BEGIN { FS = "=" } ; { print $2}' | pbcopy )
shortURLs.append(shortURL)
copy_string = "\n".join(shortURLs)
os.system( "echo '%s' | pbcopy" % (copy_string) ) # put the string into clipboard
But my problem is, how to put the correct URL in the command? As u can see it says http://link.com But it should use thisURL instead.
Any ideas? Thanks in advance!

I think your os.system call should look something like this:
os.system("curl -s --data-urlencode \"url=%s\" http://goo.gl/action/shorten | grep \"goo.gl\" | awk -F\\\" '{print $(NF-1)}' | awk 'BEGIN { FS = \"=\" } ; { print $2}' | pbcopy " % thisURL)

UPDATE I wrote the script for you and used a much simpler command pipeline. Not that the entire thing could be done in python without curl, but here it is.
import subprocess
thisURL = 'http://whatever.com'
pipeline = []
pipeline.append('curl -s -i --data-urlencode "url=%s" ' % thisURL +
'http://goo.gl/action/shorten')
pipeline.append('grep Location:')
pipeline.append('cut -d = -f 2-')
#pipeline.append('pbcopy')
command = "|".join(pipeline)
link, ignore = subprocess.Popen(command, stdout=subprocess.PIPE,
shell=True).communicate()
print link

Other answers have already provided the core of this: use quotation marks around your command, use a format string to insert the value and consider using subprocess in order to actually get the output from the command.
However, if you, like me, think this is getting a bit too convoluted, go have a look at this example on how to do the actual shortening in python. If you're new to python, this might mean you'll need to read up on your exception handling to understand it. (It also looks like you might need a custom module, but then again it appears to only be used if you get an exception...)

Related

Execute a bash command with parameter in Python

This is a bash command that I run in python and get the expected result:
count = subprocess.Popen("ps -ef | grep app | wc -l", stdout=subprocess.PIPE, shell=True)
but when I'd like to pass an argument (count in this case) cannot figure out how to do it.
I tried:
pid = subprocess.call("ps -ef | grep app | awk -v n=' + str(count), 'NR==n | awk \'{print $2}\'", shell=True)
and
args = shlex.split('ps -ef | grep app | awk -v n=' + str(count), 'NR==n | awk \'{print $2}\'')
pid = subprocess.Popen(args, stdout=subprocess.PIPE, shell=True)
among other attempts, from various posts here, but still cannot make it.
You're mixing opening and closing quotations and you pass a colon by mistake on your other attempts among other things.
Try this for a fix:
pid = subprocess.call("ps -ef | grep app | awk -v n=" + str(count) + " NR==n | awk '{print $2}'", shell=True)
You opened the command parameter with " and there for you need to close it before you do + str() with a " and not a '. Further more i swapped the , 'NR= with + "NR= since you want to append more to your command and not pass a argument to subprocess.call().
As pointed out in the comments, there's no point in splitting the command with shlex since piping commands isn't implemented in subprocess, I would however like to point out that using shell=True is usually not recommended because for instance one of the examples given here.
An other vay is using format:
pid = subprocess.call("ps -ef | grep app | awk -v n={} NR==n | awk '{{print $2}}'".format(str(count)), shell=True)
Your Awk pipeline could be simplified a great deal - if the goal is to print the last match, ps -ef | awk '/app/ { p=$2 } END { print p }' does that. But many times, running Awk from Python is just silly, and performing the filtering in Python is convenient and easy, as well as obviously more efficient (you save not only the Awk process, but also the pesky shell=True).
for p in subprocess.check_output(['ps', '-ef']).split('\n'):
if 'app' in p:
pid = p.split()[1]

python subprocess output without \n

Here is a simple script running subprocess that retrieves IP from the ifconfig command output from the terminal.
I have noticed that subprocess.check_output() always returns a value with \n.
I desire to get a return value without \n.
How can this be done?
$ python
>>> import subprocess
>>> subprocess.check_output("ifconfig en0 | awk '{ print $2}' | grep -E -o '([0-9]{1,3}[\.]){3}[0-9]{1,3}'", shell=True)
'129.194.246.245\n'
For a generic way :
subprocess.check_output("echo hello world", shell=True).strip()
subprocess.check_output() does not add a newline. echo does. You can use the -n switch to suppress the newline, but you have to avoid using the shell built-in implementation (so use /bin/echo):
>>> import subprocess
>>> subprocess.check_output('/bin/echo -n hello world', shell=True)
'hello world'
If you use echo -n instead, you could get the string '-n hello world\n', as not all sh implementations support the -n switch support echo (OS X for example).
You could always use str.rstrip() or str.strip() to remove whitespace, of course, but don't blame subprocess here:
>>> subprocess.check_output('echo hello world', shell=True).rstrip('\n')
'hello world'
Your question update added a more complex example using awk and grep:
subprocess.check_output("ifconfig en0 | awk '{ print $2}' | grep -E -o '([0-9]{1,3}[\.]){3}[0-9]{1,3}'", shell=True)
Here grep adds the (final) newline. grep -o may print just the matching text, but still adds a newline to separate matches. See the grep manual:
-o
--only-matching
Print only the matched (non-empty) parts of matching lines, with each such part on a separate output line.
Emphasis mine.
You can add a tr -d '\n' at the end to remove any newlines from the output of your pipe:
>>> subprocess.check_output(
... "ifconfig en0 | awk '{ print $2}' | "
... "grep -E -o '([0-9]{1,3}[\.]){3}[0-9]{1,3}' | "
... "tr -d '\n'", shell=True)
'172.17.174.160'
You can str.rstrip any newline or use what Martijn suggests, you can also parse the output using python with the need to awk or grep which won't add any newlines:
You can split:
out = subprocess.check_output(["ifconfig", "en0"])
for line in out.splitlines():
if line.lstrip().startswith("inet "):
print(line.split()[1].split(":", 2)[1])
print(ip.search(line))
break
Or use your own regex:
import re
out = subprocess.check_output(["ifconfig", "en0"])
print(re.search('([0-9]{1,3}[\.]){3}[0-9]{1,3}', out).group())
The point being you don't need awk or grep.
If you want to match ipv4 or ipv6 and also catch when there is an error returned i.e no such interface you can catch a CalledProcessError which will be raised for any non zero exit status, it is easy use the regex for ipv4 but for ipv6 it is simpler to use inet6 to grab the ipv6 address.
from subprocess import check_output, CalledProcessError
import re
def get_ip(iface, ipv="ipv4"):
try:
out = check_output(["ifconfig", iface])
except CalledProcessError as e:
print(e.message)
return False
try:
if ipv == "ipv4":
return re.search('([0-9]{1,3}[\.]){3}[0-9]{1,3}', out).group()
return re.search("(?<=inet6 addr:)(.*?)(?=/)", out).group().lstrip()
except AttributeError as e:
print("No {} address for interface {}".format(ipv, iface))
return False
Demo:
In [2]: get_ip("wlan0")
Out[2]: '192.168.43.168'
In [3]: get_ip("wlan0","ipv6")
Out[3]: 'fe80::120b:a9ff:fe03:bb10'
In [4]: get_ip("wlan1","ipv6")
wlan1: error fetching interface information: Device not found
Out[4]: False
This is what you have :
$ python
>>> import subprocess
>>> subprocess.check_output("ifconfig eth0 | awk '{ print $2}' | grep -E -o '([0-9]{1,3}[\.]){3}[0-9]{1,3}'", shell=True)
'172.31.94.116\n'
Try this instead :
$ python
>>> import subprocess
>>> subprocess.check_output("ifconfig eth0 | awk '{ print $2}' | grep -E -o '([0-9]{1,3}[\.]){3}[0-9]{1,3}'", shell=True).strip()
'172.31.94.116'

Python improper string quote

Hi I am embedding a shell script in python which I wanna execute as echo args Where
args = """-ne '#!/bin/sh\n\
update_bridge_config () {\n\
if [ $DATA_BRIDGE_IF ]; then\n\
echo "DATA_BRIDGE_IF is $DATA_BRIDGE_IF"\n\
sudo /usr/bin/ovs-vsctl --may-exist add-br "br-$DATA_BRIDGE_IF"\n\
fi\n\
}\n\
ETH0_MAC_ADDR=`ip link show eth0 | awk '/ether/ {print $2}'`\n\
ETH1_MAC_ADDR=`ip link show eth1 | awk '/ether/ {print $2}'`\n\
ETH2_MAC_ADDR=`ip link show eth2 | awk '/ether/ {print $2}'`\n\ ' >> myScript.sh"""
When I open the file I found those particular line is getting changed as
ETH0_MAC_ADDR= 'ip link show eth0 | awk /ether/ {print }'
Any idea what am missing ?
EDIT:: Look the ` are getting replaced by ‘ . And the ‘ are missing as well as $2
It's a single quote issue because you are starting with a single quote right after ne """-ne '#!/bin/sh ... . Because of this you are not getting $2 and facing other single quote abnormalities.
Use '"'"' to escape '
ETH0_MAC_ADDR=ip link show eth0 | awk '"'"'/ether/ {print $2}'"'"'
This should work. Mind it ! this issue is not pythonic but shell

Python - all the print and stdout how can i get from terminal so that i can make a log?

Why it does not give output while doing from bash >>, so that it can be saved to a file.
$ cat > /var/tmp/runme.sh << \EOF
#!/bin/bash
export DISPLAY=:0.0
python /var/tmp/t.py >> /var/tmp/log.log &
sleep 3
ps aux | grep "t.py" | grep -v "grep" | awk '{print $2}' | xargs kill -9;
EOF
$ cat > /var/tmp/t.py << \EOF
import sys
print "[RAN]: OK"
sys.stdout.write("[RAN]: OK")
sys.stdout.flush()
EOF
$ chmod +x /var/tmp/runme.sh ; /var/tmp/runme.sh &
$ cat /var/tmp/log.log
$ tail -f /var/tmp/log.log
^
Showing nothing.
How can i get the outputs to log.log using Bash and Python combination?
you could have python do:
var = "hello world"
f = open('log.log', 'r+')
print(var)
f.write(var)
Within var/tmp/t.py, do something similar to the following:
var = "[RAN]: OK"
f = open("log.log", "a+")
f.write(var)
print var
f.close()
Opening "log.log" with the "a+" argument will allow you to append the output of t.py to the file so that you can keep track of multiple runs of t.py. If you just want the output for the most recent run you could just use "w+" which will create a new file if one does not exist and rewrite the file if it does.
You could also put a time stamp on each log using datetime like so:
import datetime
now = datetime.datetime.now()
var = "Date: " + now.strftime("%Y-%m-%d %H:%M") + "\n" + "[RAN]: OK"
f = open("log.log", "a+")
f.write(var)
print var
f.close()
I don't know if this script is something you will run periodically in which knowing the date the log was created would be useful or whether it is a one and done script but I thought you may find date logging useful.

Python Convert Lines into a list

I use ifconfig command with awk to catch system's ip addresses
$ ifconfig | grep -E 'inet.[0-9]' | awk '{ print $2}'
127.0.0.1
192.168.8.2
How to convert o/p into a list using python ?
import sys
list_of_lines = [line.strip() for line in sys.stdin]
You might just skip shelling out to call a pipeline of commands. You can get the IP addresses without leaving Python. If you just need the non-loopback IP:
>>> socket.gethostbyname_ex(socket.gethostname())
('furby.home', [], ['192.168.1.5'])
>>> socket.gethostbyname_ex(socket.gethostname())[2][0]
'192.168.1.5'
And to get the loopback,
>>> socket.gethostbyname_ex('localhost')
('localhost', [], ['127.0.0.1'])
There's also a module called netifaces that'll do this in one fell swoop.
import subprocess
lines = subprocess.check_output(["ifconfig | grep -E 'inet.[0-9]' | awk '{ print $2
}'"]).split('\n')
Thanks all . I could do this way.
ipa=[]
f=os.popen("ifconfig | grep -E 'inet.[0-9]' | awk '{ print $2}'")
for i in f.readlines():
ipa.append(i.rstrip('\n'))
return ipa
I just modified the code posted by #Pujan to make it work for linux. (tested in Ubuntu 12.04):
import os
ipa=[]
f=os.popen("/sbin/ifconfig | grep -i \"inet\" | grep -iv \"inet6\" | " + "awk {'print $2'} | sed -ne 's/addr\:/ /p'")
for i in f.readlines():
ipa.append(i.rstrip('\n'))
print ipa
Use sys.stdin to read this output.
Then redirect the output as follows:
$ ifconfig | grep -E 'inet.[0-9]' | awk '{ print $2}' | myProg.py

Categories