[英]How to create our own linux command for python code file
我是python的新手。 作为我项目的一部分,我正在尝试为我已经拥有的python文件创建一个linux命令。 例如我有一个python文件example.py,
with open('file.txt','r') as f:
for i in f:
print i
with open('file.txt','r') as f: #for different reasons I am opening file again
for i in f:
print i
在这里,我正在尝试执行类似$example --print file.txt
的命令。 这意味着我要从命令本身提供输入文件。 然后,它必须打印输入文件的内容。 请帮助我如何实现这一目标。 提前致谢。
您需要将解释器添加到脚本的开头,还需要使用sys.env
来访问输入参数:
#!/usr/bin/python
import sys, os;
# check so we have enough arguments
if len(sys.argv) < 2:
printf "You need to supply at least two arguments."
exit(-1)
# check so the file exists
if os.path.exists(sys.argv[1]):
# try to open the filename supplied in the second argument
# the sys.argv[0] always points to the name of the script
with open(sys.argv[1], 'r') as f:
for i in f:
print i
else:
print 'The file %s does not exists' %(sys.argv[1])
请注意,您可能需要将/usr/bin/python
更改为python二进制文件的安装路径。 您可以通过发出以下命令来找出问题所在:
whereis python
现在,您应该能够像这样运行命令:
./command file.txt
请注意,这里我假设您与python脚本位于同一文件夹中。 您也可以将脚本移动到$PATH
环境变量中的文件夹中,以便可以从任何地方访问它。 例如,您可以将其移动到/usr/local/bin
:
mv command /usr/local/bin/.
然后,您应该可以使用以下命令从任何文件夹中运行它:
command file.txt
您需要做的最后一件事是确保脚本是可执行的:
chmod +x command
您需要以下内容:
#!/usr/bin/env python
sys.argv
是包含命令行参数的列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.