从命令行、Linux 中使用函数执行 python 脚本
我有一个名为convertImage.py的python文件,在文件中我有一个脚本可以根据我的喜好转换图像,整个转换脚本设置在一个名为convertFile(fileName)的函数内
现在我的问题是我需要执行这个python脚本从linux命令行,同时传递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 命令行正确传递给函数的正确方法是什么?
提前致谢
I have my python file called convertImage.py and inside the file I have a script that converts an image to my liking, the entire converting script is set inside a function called convertFile(fileName)
Now my problem is I need to execute this python script from the linux command line while passing the convertFile(fileName) function along with it.
example:
linux user$: python convertImage.py convertFile(fileName)
This should execute the python script passing the appropriate function.
example:
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
What is the right way to execute this python script and properly pass the file name to the function from the liunx command line?
Thank in advanced
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这
这会起作用。但这非常危险。
您确实需要考虑您的命令行语法是什么。您需要考虑为什么要打破长期以来为程序指定参数的 Linux 标准。
例如,您应该考虑删除示例中无用的
()
。改为这样吧。然后,您可以 - 只需很少的工作 - 使用 argparse 来获取命令(“convertFile”)和参数(“fileName”)并在标准 Linux 命令行语法中工作。
This
This will work. But it's insanely dangerous.
You really need to think about what your command-line syntax is. And you need to think about why you're breaking the long-established Linux standards for specifying arguments to a program.
For example, you should consider removing the useless
()
's in your example. Make it this, instead.Then, you can -- with little work -- use
argparse
to get the command ("convertFile") and the arguments ("fileName") and work within the standard Linux command line syntax.快速而肮脏的方法:
然后在convertImage.py中
更复杂的方法是使用 argparse(适用于 2.7 或 3.2+)或 optparse。
Quick and dirty way:
and then in convertImage.py
A more sophisticated approach would use argparse (for 2.7 or 3.2+) or optparse.
创建脚本的顶级可执行部分,用于解析命令行参数,然后将其传递给调用中的函数,如下所示:
然后,从 shell,
Create a top-level executable part of your script that parses command-line argument(s) and then pass it to your function in a call, like so:
Then, from a shell,