日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

關于命令行執行Python腳本的傳參方式_python

作者:Tangctt ? 更新時間: 2022-10-31 編程語言

命令行執行Python腳本的傳參

應用場景

  • 在對ABAQUS進行二次開發時,需要將核心腳本的外部數據傳遞到腳本內部并執行
  • 核心腳本在運行時,可以調用所傳遞的變量參數
  • 命令行執行或者用戶子程序執行

方式一

使用sys.args

簡單示例

import sys

def test_sys_args():
? ? if len(sys.argv) > 1:
? ? ? ? print(len(sys.argv) - 1)
? ? ? ? print(sys.argv)
? ? else:
? ? ? ? print('無參數輸入')
if __name__ == '__main__':
? ? test_sys_args()

執行

python test.py a 1 test

腳本文件名后面的是需要傳遞的參數

其它參數在命令行中傳入時需要用空格分開

若參數中需要包含“”,則需要使用到轉義字符\進行轉義

輸出結果

3
['test.py', 'a', '1', 'test']

  • 3代表著傳遞參數的數量
  • sys.args實現從程序外部向程序傳遞參數,它的值是一個列表list,其中保存了通過命令行傳遞的各個參數
  • 輸出sys.argv[0],即為第一個參數,是腳本本身
  • sys.argv[1]的輸出結果為a

所以在二次開發的仿真腳本中,使用子程序進或命令行運行腳本,且需要使用此種方式進行傳參時,需要將變量及其參數一并傳遞,具體使用方式如下

#執行腳本
child_process.exec(command val1=1 val2=2 val3=3)

腳本內部

sys.argv[1]輸出結果為val1=1

滿足腳本對的變量需求,成功將腳本外的參數傳遞到腳本內

方式二

創建獨立腳本參數文件

  • 使用node.js的文本操作fs模塊
  • 在python的運行目錄下創建單獨的變量數據txt文件夾
  • 先讀取變量數據,然后將變量根據格式拼接,最后將其寫入單獨的文本文件
  • 在執行python腳本時,只需在腳本中運行目錄下的文本文件,就完成了參數的傳遞工作

如下所示

node.js后端

var fs = require('fs')

fs.writeFile('test.txt', _registerMsg, function (err) {

? ? ? ? if (err) {
? ? ? ? ? ? return console.log(err);
? ? ? ? } else {
? ? ? ? ? ? // 變量文件創建成功后,執行核心計算腳本
? ? ? ? ? ? exec("abaqus cae nogui=abaqus.py", function (error, stdout, stderr) {
? ? ? ? ? ? ? ? if (stdout.length > 1) {
? ? ? ? ? ? ? ? ? ? // 計算成功
? ? ? ? ? ? ? ? ? ? console.log('you offer args:', stdout);
? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? // 計算失敗
? ? ? ? ? ? ? ? ? ? console.log('you don\'t offer args');
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? if (error) {
? ? ? ? ? ? ? ? ? ? console.info('stderr : ' + stderr);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? })

? ? ? ? }
? ? })

腳本所需參數已經提前拼接并寫入到_registerMsg變量中

python腳本

import io
with io.open("test.txt", encoding='utf-8') as f:
? ? code = f.read()
exec(code)

腳本只需打開同目錄下的參數文件并執行,即可將參數傳遞到腳本中

兩種方式的優缺點

  • 第一種方式能夠對每個參數進行單獨讀取,但是也需要進行單獨輸出
  • 當需要傳遞參數較多時,每次運行腳本都要進行輸入,工作量較大
  • 第二種方式將參數進行了集成,只需調整腳本中的變量,集合進行參數的修改
  • 在面向較多的參數時便于對參數的操作,能夠提升效率

python-命令行傳參sys.argv實際運用

平常我們在用別人寫好的python包的時候,在cmd輸入xx -h就能查看到幫助信息,輸入xx -p 8080就能把參數傳入程序里,看起來非常酷。

本篇就來講下如何在python代碼里加入命令行參數,并且其它功能,能調用這個參數。

argv獲取參數

Python 中也可以所用 sys 的 sys.argv 來獲取命令行參數:

  • sys.argv 是命令行參數列表。
  • len(sys.argv) 是命令行參數個數。

注:sys.argv[0] 表示腳本名。

test.py代碼如下

# -*- coding: UTF-8 -*-
import sys
?
print '參數個數為:', len(sys.argv), '個參數。'
print '參數列表:', str(sys.argv)

執行以上代碼,輸出結果為:

$ python test.py arg1 arg2 arg3
參數個數為: 4 個參數。
參數列表: ['test.py', 'arg1', 'arg2', 'arg3']

getopt模塊

getopt模塊是專門處理命令行參數的模塊,用于獲取命令行選項和參數,也就是sys.argv。命令行選項使得程序的參數更加靈活。支持短選項模式(-)和長選項模式(--)。

該模塊提供了兩個方法及一個異常處理(Exception getopt.GetoptError)來解析命令行參數。

getopt.getopt 方法用于解析命令行參數列表,語法格式如下:

getopt.getopt(args, options[, long_options])

參數說明:

  • args: 要解析的命令行參數列表。
  • options: 以列表的格式定義,options后的冒號(:)表示該選項必須有附加的參數,不帶冒號表示該選項不附加參數。
  • long_options: 以字符串的格式定義,long_options 后的等號(=)表示如果設置該選項,必須有附加的參數,否則就不附加參數。
  • 該方法返回值由兩個元素組成: 第一個是 (option, value) 元組的列表。 第二個是參數列表,包含那些沒有'-'或'--'的參數。

實例

假定我們創建這樣一個腳本,可以通過命令行向腳本文件傳遞兩個文件名,同時我們通過另外一個選項查看腳本的使用。腳本使用方法如下:

$ test.py -i -o

test.py 文件代碼如下所示:

# -*- coding: UTF-8 -*-
?
import sys, getopt
?
def main(argv):
? ?inputfile = ''
? ?outputfile = ''
? ?try:
? ? ? opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
? ?except getopt.GetoptError:
? ? ? print 'test.py -i <inputfile> -o <outputfile>'
? ? ? sys.exit(2)
? ?for opt, arg in opts:
? ? ? if opt == '-h':
? ? ? ? ?print 'test.py -i <inputfile> -o <outputfile>'
? ? ? ? ?sys.exit()
? ? ? elif opt in ("-i", "--ifile"):
? ? ? ? ?inputfile = arg
? ? ? elif opt in ("-o", "--ofile"):
? ? ? ? ?outputfile = arg
? ?print '輸入的文件為:', inputfile
? ?print '輸出的文件為:', outputfile
?
if __name__ == "__main__":
? ?main(sys.argv[1:])

執行以上代碼,輸出結果為:

$ python test.py -h
usage: test.py -i <inputfile> -o <outputfile>
?
$ python test.py -i inputfile -o outputfile
輸入的文件為: inputfile
輸出的文件為: outputfile

實際場景運用

結合selenium測試,比如我想測試chrome瀏覽器,那就在命令行輸入“chrome”參數,想測試firefox瀏覽器的時候,就在命令行輸入“firefox”參數,這樣就能靈活切換不同瀏覽器之間的測試了

# 保存為run.py
?
# coding:utf-8
import sys, getopt
from selenium import webdriver
import time
?
def main(argv):
? ? '''
? ? 命令行傳參
? ? 上海-悠悠博客:https://www.cnblogs.com/yoyoketang/
? ? '''
? ? name = "firefox" # 給個默認值
?
? ? try:
? ? ? ? # 這里的 h 就表示該選項無參數,n:表示 n 選項后需要有參數
? ? ? ? opts, args = getopt.getopt(argv, "hn:", ["name="])
? ? except getopt.GetoptError:
? ? ? ? print('Error: test_yoyo.py -n <browsername>')
? ? ? ? print(' ? or: test_yoyo.py --name=<browsername>')
? ? ? ? sys.exit(2)
?
? ? for opt, arg in opts:
? ? ? ? if opt == "-h":
? ? ? ? ? ? print('test_yoyo.py -n <browsername>')
? ? ? ? ? ? print('or: test_yoyo.py --name=<browsername>')
? ? ? ? ? ? sys.exit()
? ? ? ? elif opt in ("-n", "--name"):
? ? ? ? ? ? name = arg
?
? ? print('run browser name : %s' % name)
? ? return name
?
def browser(n=None):
? ? '''
? ? 啟動瀏覽器, n是瀏覽器名稱,支持瀏覽器:chrome ,firefox
? ? 上海-悠悠博客:https://www.cnblogs.com/yoyoketang/
? ? '''
? ? if n == None:
? ? ? ? name = main(sys.argv[1:])
? ? else:
? ? ? ? name = n
? ? if name == "firefox":
? ? ? ? print("當前執行瀏覽器:%s" % name)
? ? ? ? return webdriver.Firefox()
? ? elif name == "chrome":
? ? ? ? print("當前執行瀏覽器:%s" % name)
? ? ? ? return webdriver.Chrome()
? ? else:
? ? ? ? print("支持瀏覽器:chrome,firefox")
?
if __name__ == "__main__":
? ? driver = browser()
? ? driver.get("https://www.cnblogs.com/yoyoketang/")
? ? t = driver.title
? ? print(t)
? ? time.sleep(10)
? ? driver.quit()

cmd執行情況

C:\Users\admin>d:
?
D:\>cd lianxi
?
D:\lianxi>python run.py -n chrome
Input name : chrome
當前執行瀏覽器:chrome
?
DevTools listening on ws://127.0.0.1:54248/devtools/browser/595fe8cf-524d-4599-9
540-2502f6a6f2ca
上海-悠悠 - 博客園
?
D:\lianxi>python run.py -n firefox
Input name : firefox
當前執行瀏覽器:firefox
上海-悠悠 - 博客園

備注:python2在cmd執行時,中文會顯示亂碼,用python3就不會有亂碼了

原文鏈接:https://blog.csdn.net/Tang__CT/article/details/124177171

欄目分類
最近更新