从命令行执行python脚本,Linux
我有我的python文件,名为convertImage.py,在文件内部我有一个脚本将图像转换为我喜欢的,整个转换脚本设置在名为convertFile(文件名)从命令行执行python脚本,Linux
现在我的问题是我需要从linux命令行执行这个python脚本,同时传递convertFile(fileName)函数。
例如:
linux user$: python convertImage.py convertFile(fileName)
这应该执行python脚本传递适当的功能。
例如:
def convertFile(fileName):
import os, sys
import Image
import string
splitName = string.split(fileName, "_")
endName = splitName[2]
splitTwo = string.split(endName, ".")
userFolder = splitTwo[0]
imageFile = "/var/www/uploads/tmp/"+fileName
...rest of the script...
return
什么是执行这个python脚本并正确传递文件名从LIUNX命令行功能的正确方法?
感谢先进
这
if __name__ == "__main__":
command= " ".join(sys.argv[1:])
eval(command)
这将工作。但它非常危险。
你真的需要思考你的命令行语法是什么。而且您需要考虑为什么要打破用于为程序指定参数的早已建立的Linux标准。
例如,您应该考虑在您的示例中删除无用的()
。相反,让它成为这个。
python convertImage.py convertFile fileName
然后,你可以 - 用很少的工作 - 使用获得标准的Linux命令行语法中的命令(“convertFile”)和参数(“文件名”)和工作。
function_map = {
'convertFile': convertFile,
'conv': convertFile,
}
parser = argparse.ArgumentParser()
parser.add_argument('command', nargs=1)
parser.add_argument('fileName', nargs='+')
args= parser.parse_args()
function = function_map[args.command]
function(args.fileName)
快速和肮脏的方式:
linux user$: python convertImage.py convertFile fileName
,然后在convertImage.py
if __name__ == '__main__':
import sys
function = getattr(sys.modules[__name__], sys.argv[1])
filename = sys.argv[2]
function(filename)
argparse也在2.7 –
@PetrViktorin:谢谢,更新。 –
创建脚本的顶层可执行部分,它分析命令行参数(S),然后将它传递给你的函数调用,就像这样:
import os, sys
#import Image
import string
def convertFile(fileName):
splitName = string.split(fileName, "_")
endName = splitName[2]
splitTwo = string.split(endName, ".")
userFolder = splitTwo[0]
imageFile = "/var/www/uploads/tmp/"+fileName
print imageFile # (rest of the script)
return
if __name__ == '__main__':
filename = sys.argv[1]
convertFile(filename)
然后,从外壳,
$ convertImage.py the_image_file.png
/var/www/uploads/tmp/the_image_file.png
-1不建议使用argparse – Kimvais
这是否需要hashbang? –
有没有这样的事情。解析'sys.argv'列表并选择正确的操作。检查'argparse'模块 – JBernardo
正如S.Lott所提到的,''是一种非常常见的风格。用户最好拥有命令名称,而不是内部实现的知识。并且使用括号(需要在bash中转义)作为语法的必需部分只是意味着什么。 –
Cascabel
括号仅仅是出于示例的原因,但我赞赏所有的帮助,并得到它使用sys.argv – knittledan