簡體   English   中英

在與 python 腳本相同的目錄中使用文件作為命令行參數時遇到問題

[英]Having trouble using a file as a command-line argument in the same directory as the python script

我正在嘗試編寫一個 .py 腳本,它將另一個文件作為命令參數,cmd-argument 文件與所述腳本位於同一目錄中。

到目前為止我所擁有的是:

import sys
java_file = open(sys.argv[1],"r")
<rest of file>

如果我有這樣的命令行參數,這很好用:

python.exe "D:\<user>\<more file directories>\balanced.py" "D:\<user>\<same file directories>\Driver.java"

我想要做的是命令行參數是這樣的:

python.exe "D:\<user>\<more file directories>\balanced.py" Driver.java

使用 Python 3.7.3 在 Windows 10 命令提示符下運行。

在 Windows 上, sys.argv[0]應該是腳本的完整路徑,因此您可以使用os.path.split(sys.argv[0])[0]來獲取路徑,然后使用os.path.join()加入它

import sys, os
java_file = open(os.path.join(os.path.split(sys.argv[0])[0], sys.argv[1]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM