![](/img/trans.png)
[英]Passing dictionary arguments through command line and accessing them in a python script
[英]arguments passing through command line in python
這個問題可能是一個愚蠢的問題。 由於這是python的新手,請在此問題上幫助我。
if __name__== '__main__' :
path=sys.argv[1]
在上面的代碼中,im從命令行讀取參數。 我的觀點是系統中某些文件的路徑。 當我不提供論據時,它會引發錯誤“列表索引超出范圍”
而不是從命令行讀取,我想以以下方式輸入
“輸入文件的路徑。”
顯示此行后,如何按Tab並通過路徑作為輸入來解析文件系統?
sys.argv
只是一個列表,說sys.argv[1]
與說args = [0]; args[1]
args = [0]; args[1]
您需要檢查索引1
確實存在
嘗試這個:
path = raw_input("enter path to your file..")
print path
如果使用的命令行參數如hello.py myfile.txt
,則使用
if len(sys.argv) > 1:
path = sys.argv[1]
更新:
如果需要向用戶顯示目錄中的所有文件。 用這個:
import os
i = 1
for item in os.listdir("F:/python/Lib"):
if os.path.isfile(os.path.join("F:/python/Lib", item)):
print str(i) + " : " + item
i += 1
輸出:
>>>
1 : abc.py
2 : abc.pyc
3 : aifc.py
4 : antigravity.py
5 : anydbm.py
6 : argparse.py
7 : ast.py
8 : asynchat.py
9 : asyncore.py
10 : atexit.py
11 : atexit.pyc
12 : audiodev.py
13 : base64.py
14 : base64.pyc
15 : BaseHTTPServer.py
16 : BaseHTTPServer.pyc
17 : Bastion.py
18 : bdb.py
19 : bdb.pyc
我如何通過按Tab鍵解析文件系統並將路徑作為輸入
這不是一件容易的事,因為按下選項卡意味着完成,它是在bash
或batch
級別(運行python程序的終端)上完成的。
您可能需要添加一個函數,該函數從os
和sys
模塊中調用適當的子例程,然后執行自定義完成。
在這里,您可以了解我的意思,希望能有所幫助。
某種無關緊要的東西 :
如果您想執行更復雜的命令行選項解析,請考慮使用argparse
模塊 。
這是我編寫的腳本中模塊的簡單演示:
import argparse
parser = argparse.ArgumentParser(description='MD5 Cracker')
parser.add_argument('target', metavar='Target_MD5_Hash', help='The target MD5 that you want to have cracked.')
parser.add_argument('--online', '-o', help='MD5 Cracker will try to crack the password using online MD5 cracking websites and databases', default=False)
parser.add_argument('--list', '-l', help='MD5 Cracker will try to crack the passwork offline with a dictionary attack using the list supplied', default=False)
parser.add_argument('--interactive', '-i', help='MD5 Cracker will enter interactive mode, allowing you to check passwords without reinitiating the software each time', default=False)
if __name__ == '__main__':
cli_args = parser.parse_args()
args_dict = cli_args.__dict__ # here it is cast into a dictionary to allow for easier manipulation of contents
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.