shell和python中互調

2021-06-22 01:59:26 字數 1151 閱讀 6310

一.在shell指令碼中呼叫python指令碼,執行結果給予賦值

#!/bin/bash

#在shell中掉用python指令碼執行結果賦值給key

key=`python /usr/local/pythonstudy/print.py`

a=$key

#對key進行過濾

b=`echo $key | awk -f\? ''`

echo $b

二.3種方法python中呼叫shell指令碼以及shell命令

#!/usr/bin/python

import os

import commands

def getstatusoutputfun():

print 'getstatusoutput fun.....'

"""a是狀態, b結果"""

a,b =commands.getstatusoutput('~/demo.sh')

print a

print b

def popenfun():

print 'popen fun .....'

str=os.popen("ifconfig").read()

print str

"""a=str.split('\n')

for b in a:

print b

"""def sysfun():

print 'system fun......'

os.system('~/demo.sh')

def test():

getstatusoutputfun()

popenfun()

sysfun()

test()

a=os.system("ls"): 命令的返回值(a)是系統命令的返回值。結果是由子shell執行的,顯示在螢幕上,無法捕捉。

a=os.popen("ls","r").read():結果可以賦於一變數,便於程式的處理。注read()的結果有"\n",用strip()加上readlines()可以得到輸出。

commands.getoutput("date")

commands.getstatusoutput("date")

python和shell之間變數的相互呼叫

python shell 1.環境變數 python view plain copy import os var 123或var 123 os.environ var str var environ的鍵值必須是字串 os.system echo var python view plain copy ...

python和shell之間變數的相互呼叫

1.環境變數 import os var 123或var 123 os.environ var str var environ的鍵值必須是字串 os.system echo var 2.字串連線 import os path root a.txt var 1 var bash os.system e...

Python 和 C語言的相互呼叫

第一種 python呼叫c動態鏈結庫 利用ctypes 下面示例在linux或unix下可行。pycall.c12 3456 78 gcc o libpycall.so shared fpic pycall.c include include intfoo inta,intb pycall.py12...