2016-11-16 45 views
0

我有下面的py腳本從artifactory下載文件。如何在基於配置文件中的變量的python腳本中調用另一個python腳本?

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

import os 
import tarfile 
import urllib 
from urllib import urlretrieve 
import ConfigParser 

Config = ConfigParser.ConfigParser() 
Config.read('/vivek/release.conf') 
code_version = Config.get('main', 'app_version') 

os.chdir('/tmp/') 
arti_st_url='http://repo.com/artifactory/libs-release- local/com/name/tgz/abc.ear/{0}/abc.ear-{0}.tar.gz'.format(code_version) 
arti_st_name='abc.ear-{0}.tar.gz'.format(code_version) 
arti_sl_url='http://repo.com/artifactory/libs-release- local/com/name/tgz/def.ear/{0}/def.ear-{0}.tar.gz'.format(code_version) 
arti_sl_name='def.ear-{0}.tar.gz'.format(code_version) 
urllib.urlretrieve(arti_st_url, arti_st_name) 
urllib.urlretrieve(arti_sl_url, arti_sl_name) 
oneEAR = 'abc.ear-{0}.tar.gz'.format(code_version) 
twoEAR = 'def.ear-{0}.tar.gz'.format(code_version) 
tar = tarfile.open(oneEAR) 
tar.extractall() 
tar.close() 
tar1 = tarfile.open(twoEAR) 
tar1.extractall() 
tar1.close() 
os.remove(oneEAR) 
os.remove(twoEAR) 

這個腳本完美工作,感謝stackoverflow。

下面是下一個問題。 release.conf中有一個變量「protocol」。如果它等於「localcopy」,則有一個現有的py腳本可以執行某些操作。如果「協議」等於「artifactory」,則應調用並執行上面的腳本 。我怎樣才能實現它?

注意:我是Python初學者,但我的任務不是。所以,請幫幫我。

回答

0

你可以簡單地使用:

進口OS

使用os.system( 「script_path」)

執行腳本文件。但是在腳本文件的最頂部應該有一行叫做shebang的行,你想執行。如果你的Python解釋器會在/ usr/bin中/ Python的,這將是:

#在/ usr/bin中/ Python的

假設你是一個Linux用戶。 在Windows中,shebang不受支持。它決定使用正在運行的* .py文件本身的程序。

//編輯: 要調用取決於屬性配置值,你可以只讓打了個比方runthis.py另一個腳本包含了像指令兩個腳本:

protocol = Config.get('main', 'protocol') 
if protocol == 'localcopy': 
    os.system('path_to_localcopy_script) 
if protocol == 'antifactory': 
    os.system('path_to_other_script') 

不要忘了導入需要的模塊在那個新的腳本。

然後,您只需運行您剛創建的腳本。

這是做到這一點的一種方法。

如果你不想創建其他腳本,然後把你在一個函數中寫道,這樣的代碼:

def main(): 
    ... 
    Your code 
    ... 

並在您的腳本文件寫的最底部:

if __name__ = '__main__': 
    protocol = Config.get('main', 'app_version') 
    if protocol == 'localcopy': 
    main() 
    if protocol == 'antifactory': 
    os.system('path_to_other_script') 

if __name__ = '__main__'只會在您自己運行該腳本時執行(例如,不能通過其他sctipt調用)

+0

感謝您的回覆Ginko。但我的問題是基於配置文件中的變量,我應該在另一個py文件中調用上面給定的py文件。 – Vivek

+0

檢查我是否幫助你完成了該編輯 – Ginko

相關問題