python脚本里执行linux命令的时候如何调用python的函数?
高洛峰
高洛峰 2017-04-18 09:29:12
0
3
481

本菜鸟有一个可以获取ip地址的脚本,如下:

def get_local_ip(ifname = 'eth1'):
    import socket, fcntl, struct
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))
    ret = socket.inet_ntoa(inet[20:24])
    return ret

print get_local_ip()

现在有一个任务,就是在linux里把一个relay.conf文件里的“RELAY_AGENT_IP = ”替换成“RELAY_AGENT_IP = 当前IP地址”,这个用sed语句很好解决:os.system("sed -i s/RELAY_AGENT_IP =/RELAY_AGENT_IP = 当前IP地址/ relay.conf")即可,但是get_local_ip()是一个函数啊,函数无法直接套用到上面那个sed语句,会报语法错误。

请问遇到这样的情况怎么破?肯定各位大大指点。

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
刘奇

The above answer is enough, just use the string template, or this expression is more friendly:

os.system("sed -i s/RELAY_AGENT_IP =/RELAY_AGENT_IP = {}/ relay.conf".format(get_local_ip()))
Ty80
os.system("sed -i s/RELAY_AGENT_IP =/RELAY_AGENT_IP = %s/ relay.conf"%(get_local_ip()))
PHPzhong

First of all, given your get_local_ip函数有问题, 并不能正常获取到本地IP address, it is recommended to look at the solution here:
http://stackoverflow.com/ques...

Also, you are using sed incorrectly. There is a syntax problem (missing double quotes), it should be like thissed用的也不对啊, 语法有问题(缺了双引号), 应该是这样
sed -i "s/RELAY_AGENT_IP =/RELAY_AGENT_IP = 当前IP地址/" relay.conf
而且这条命令只能是把
RELAY_AGENT_IP =这个替换成RELAY_AGENT_IP = 当前IP地址而已, 如果你的relay.conf文件这一行原本就有IP地址值呢?比如这样RELAY_AGENT_IP = 1.2.3.4照你这个命令替换完是这个样子RELAY_AGENT_IP = 当前IP地址1.2.3.4, 为了有一定的错误格式容忍度, 最好用正则来匹配, 比如
sed -i "s/^RELAY_AGENT_IP.*/RELAY_AGENT_IP = 我爱北京天安门/" relay.confsed -i "s/RELAY_AGENT_IP =/RELAY_AGENT_IP = current IP address /" relay.conf

And this command can only replace 🎜RELAY_AGENT_IP = with RELAY_AGENT_IP = current IP address. If your relay.conf file originally have an IP address value? For example, RELAY_AGENT_IP = 1.2.3.4 After replacing it with your command, it will look like this RELAY_AGENT_IP = current IP address 1.2.3.4, in order to have a certain tolerance for format errors, it is best to use regular expressions for matching, such as 🎜sed -i "s/^RELAY_AGENT_IP.*/RELAY_AGENT_IP = I love Beijing Tiananmen/" relay. conf🎜
$ cat relay.conf
RELAY_AGENT_IP = 我爱北京天安门
$ sed "s/^RELAY_AGENT_IP.*/RELAY_AGENT_IP = 天安门上太阳升/" relay.conf
RELAY_AGENT_IP = 天安门上太阳升
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template