[英]running python function with arguments from cmd.exe
我有帶1個參數的Python函數
def build_ibs(Nthreads,LibCfg): # Nthreads is int,LibCfg as string
import os # module os must be imported
import subprocess
import sys
我在cmd.exe(在Win7上)中使用以下命令來調用它
C:>cd C:\SVN\Python Code
C:\SVN\Python Code>C:\Python27\python.exe build_libs(4,'Release')
C:>cd C:\SVN\Python Code
C:\SVN\Python Code>C:\Python27\python.exe 4 'Release' # dosn't work
C:\SVN\Python Code>C:\Python27\python.exe 4 Release # dosn't work
什么也不做,甚至不會顯示任何錯誤。
在cmd.exe甚至Python Shell命令行中調用它的正確方法是什么?
謝謝
塞迪
您不能只從命令行調用函數-它必須在文件內部。 在命令行中輸入python filename.py
時,其作用是將filename.py
的內容輸入到名稱空間設置為__main__
的Python解釋器中。
因此,當您鍵入Python.exe 4 'Release'
它將嘗試查找名為4
的文件。 由於此文件不存在,Windows將返回Errno 2-找不到文件。
相反,將您的代碼放入文件中-假設test.py :
test.py :
def build_libs(Nthreads,LibCfg): # Nthreads is int,LibCfg as string
import os # module os must be imported
import subprocess
import sys
# ...
if __name__=='__main__':
numthreads = sys.argv[1] # first argument to script - 4
libconfig = sys.argv[2] # second argument
# call build_libs however you planned
build_libs(numthreads, libconfig)
然后從命令行運行: C:\\Python27\\python.exe test.py 4 Release
在保存test.py的目錄中。
更新:如果需要在多個文件中使用build_libs
,最好在模塊中定義它,然后將其導入。 例如:
mod_libs / __ init__.py-空文件
mod_libs / core.py :
def build_libs(...):
....
# function definition goes here
test.py :
import sys
import mod_libs
if __name__ == '__main__':
mod_libs.build_libs(sys.argv[1], sys.argv[2])
sys.argv
或argparse
)。 例如:
C:\SVN\Python Code> py
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import build_libs
>>> build_libs.build_libs(4, 'Release')
或者,在build_libs.py
,在腳本頂部導入sys
模塊,然后在腳本末尾基於其參數運行該函數:
import sys
...
print(build_libs(int(sys.argv[1]), sys.argv[2]))
然后在您的操作系統的命令行中:
C:\SVN\Python Code> py build_libs 4 Release
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.