2017-04-11 32 views
-1

我是python的新手。作爲我的項目的一部分,我正在嘗試爲我已經有的python文件創建一個linux命令。比如我有一個python文件example.py,如何爲python代碼文件創建我們自己的linux命令

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。 這意味着我正在從命令本身提供輸入文件。然後它必須打印輸入文件的內容。 請幫助我如何實現這一點。 在此先感謝。

+0

的[我用什麼在Linux上做一個Python程序可執行文件(可能的複製http://stackoverflow.com/questions/304883/what-do-i-use-on -linux對做-A-python的程序可執行) – tripleee

回答

2

你需要解釋添加到頭部列表您還可以使用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 

你需要做的最後一件事是確保該腳本是可執行的:

chmod +x command 
+0

不要忘記讓腳本可執行:'chmod + x command'。 –

+0

@SvenFestersen - 我打算從一開始就包含chmod命令,但我忘記了=) – Cyclonecode

+0

感謝您的答案@Cyclonecode。你能告訴我如何在命令中輸入多個文件作爲輸入。 – sowji

0

您需要:

  1. 腳本的開頭應具有#!/usr/bin/env python
  2. sys.argv是包含您的命令行參數
相關問題