SoFunction
Updated on 2024-10-29

About the way to pass parameters for executing Python scripts from the command line

Passing Parameters for Executing Python Scripts on the Command Line

application scenario

  • In secondary development of ABAQUS, external data from the core script needs to be passed inside the script and executed
  • The core script can call the passed variable parameters at runtime
  • Command line execution or user subroutine execution

Mode 1

utilization

simple example

import sys

def test_sys_args():
    if len() > 1:
        print(len() - 1)
        print()
    else:
        print('No parameter input')
if __name__ == '__main__':
    test_sys_args()

fulfillment

python  a 1 test

The name of the script file is followed by the parameters to be passed.

Other parameters need to be separated by spaces when passed on the command line

If the parameter needs to contain "", you need to use the escape character \ for escaping.

output result

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

  • 3 represents the number of parameters passed
  • Implements the passing of parameters to a program from outside the program, whose value is a list of lists that hold the individual parameters passed via the command line
  • Output [0], which is the first parameter, is the script itself
  • The output of [1] is a

Therefore, in the secondary development of the simulation script, use the subroutine or command line to run the script, and need to use this way to pass the parameter, you need to pass the variable and its parameters together, the specific use of the following way

# Execute the script
child_process.exec(command val1=1 val2=2 val3=3)

Script Internal

[1] Output results in val1=1

Satisfy the variable requirements of script pairs and successfully pass parameters from outside the script to inside the script.

Mode 2

Creating a standalone script parameter file

  • Text manipulation fs modules used
  • Create a separate variable data txt folder in python's run directory
  • First read the variable data, then splice the variables according to the format, and finally write them to a separate text file
  • When executing a python script, you simply run the text file in the directory in the script, and you're done passing parameters around

as shown below

back end

var fs = require('fs')

('', _registerMsg, function (err) {

        if (err) {
            return (err);
        } else {
            // After the variable file has been successfully created, execute the core computation scripts
            exec("abaqus cae nogui=", function (error, stdout, stderr) {
                if ( > 1) {
                    // Calculated successfully
                    ('you offer args:', stdout);
                } else {
                    // Calculation failure
                    ('you don\'t offer args');
                }
                if (error) {
                    ('stderr : ' + stderr);
                }
            })

        }
    })

The parameters needed for the script have been spliced and written to the _registerMsg variable in advance

python script

import io
with ("", encoding='utf-8') as f:
    code = ()
exec(code)

The script simply opens a parameter file in the same directory and executes it to pass the parameters to the script

Advantages and disadvantages of both approaches

  • The first way is able to read each parameter individually, but it also requires individual outputs
  • When more parameters need to be passed, input is required each time the script is run, which is a lot of work
  • The second way integrates the parameters, only need to adjust the variables in the script, the collection for parameter modification
  • Facilitates parameter manipulation and improves efficiency when dealing with a large number of parameters.

Python-Command Line Passing in Practice

Normally when we're using a python package written by someone else, it looks pretty cool to type xx -h in cmd to see the help information and xx -p 8080 to pass parameters into the program.

In this post, we will talk about how to add a command line parameter to python code, and other functions, which can call this parameter.

argv gets the arguments

Python can also use sys to get command-line arguments:

  • is a list of command line arguments.
  • len() is the number of command line arguments.

Note: [0] indicates the script name.

The code is as follows

# -*- coding: UTF-8 -*-
import sys
 
print 'The number of parameters is:', len(), 'A parameter.'
print 'Parameter list:', str()

Execute the above code and the output will be:

$ python arg1 arg2 arg3
The number of parameters is: 4 parameters.
Argument list: ['', 'arg1', 'arg2', 'arg3']

getopt module

The getopt module is a module specialized in handling command line arguments for getting command line options and arguments, that is. Command line options make the program parameters more flexible. Short option mode (-) and long option mode (--) are supported.

The module provides two methods and an Exception to parse command line arguments.

method is used to parse a list of command line arguments with the following syntax format:

(args, options[, long_options])

Parameter Description:

  • args: List of command line arguments to parse.
  • options: Defined as a list, a colon (:) after options means the option must have additional arguments, no colon means the option does not have additional arguments.
  • long_options: Defined in string format, the equal sign (=) after long_options means that if the option is set, there must be an additional parameter, otherwise no parameter is attached.
  • The method return value consists of two elements: the first is a list of (option, value) tuples. The second is a list of arguments, containing those without '-' or '--'.

an actual example

Assuming we create such a script, we can pass two filenames to the script file via the command line, while we view the script usage via another option. The script usage is as follows:

$  -i -o

The file code is shown below:

# -*- coding: UTF-8 -*-
 
import sys, getopt
 
def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = (argv,"hi:o:",["ifile=","ofile="])
   except :
      print ' -i <inputfile> -o <outputfile>'
      (2)
   for opt, arg in opts:
      if opt == '-h':
         print ' -i <inputfile> -o <outputfile>'
         ()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print 'The input file is:', inputfile
   print 'The output file is:', outputfile
 
if __name__ == "__main__":
   main([1:])

Execute the above code and the output will be:

$ python -h
usage: -i <inputfile> -o <outputfile>
 
$ python -i inputfile -o outputfile
The input file is: inputfile
The output file is: outputfile

Practical scenarios

For example, if I want to test chrome browser, I will enter "chrome" as a parameter on the command line, and if I want to test firefox browser, I will enter "firefox" as a parameter on the command line. parameter on the command line, so you can flexibly switch between different browsers.

# Save as
 
# coding:utf-8
import sys, getopt
from selenium import webdriver
import time
 
def main(argv):
    '''
    Command Line Passing Parameters
    Shanghai-Yoyo Blog:/yoyoketang/
    '''
    name = "firefox" # Give a default
 
    try:
        # The h here means that the option has no arguments, and the n: means that the n option needs to be followed by an argument.
        opts, args = (argv, "hn:", ["name="])
    except :
        print('Error: test_yoyo.py -n <browsername>')
        print('   or: test_yoyo.py --name=<browsername>')
        (2)
 
    for opt, arg in opts:
        if opt == "-h":
            print('test_yoyo.py -n <browsername>')
            print('or: test_yoyo.py --name=<browsername>')
            ()
        elif opt in ("-n", "--name"):
            name = arg
 
    print('run browser name : %s' % name)
    return name
 
def browser(n=None):
    '''
    Start browser, n is the browser name, support browser: chrome ,firefox
    Shanghai-Yoyo Blog:/yoyoketang/
    '''
    if n == None:
        name = main([1:])
    else:
        name = n
    if name == "firefox":
        print("Current execution browser: %s" % name)
        return ()
    elif name == "chrome":
        print("Current execution browser: %s" % name)
        return ()
    else:
        print("Supported browsers: chrome,firefox")
 
if __name__ == "__main__":
    driver = browser()
    ("/yoyoketang/")
    t = 
    print(t)
    (10)
    ()

cmd execution

C:\Users\admin>d:
 
D:\>cd lianxi
 
D:\lianxi>python  -n chrome
Input name : chrome
Current Executive Browser:chrome
 
DevTools listening on ws://127.0.0.1:54248/devtools/browser/595fe8cf-524d-4599-9
540-2502f6a6f2ca
Shanghai-a great number (of events) - blogosphere
 
D:\lianxi>python  -n firefox
Input name : firefox
Current Executive Browser:firefox
Shanghai-a great number (of events) - blogosphere

Note: python2 in cmd execution, the Chinese will display garbled code, with python3 will not have garbled code

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.