如何在 Python 中将 `ENV` 文件变量和 运行 作为单个命令读取

How can I read the `ENV` file variables and run as single command in Python

如何读取 dev.ENV 文件并将以下五个变量放入 python 脚本和 运行 作为 windows 命令提示符中的单个命令。

dev.ENV file

CYPRESS_baseUrl=https://someurl.com
runCyCommand=npx cypress-tags run 
tags=-e TAGS='@limitedRun' 
path=GLOB='tests/cypress/integration/**/*.feature'
config= --headless --browser chrome

demoTest.py

f = open("C:/Test/dev.ENV", "r")
with open("C:/Test/dev.ENV", mode="r", encoding="utf-8") as my_file:  # Open file for reading
for line in my_file.readlines():  # Read all lines one-by-one
print("\nPassword: {}".format(line.strip())) 

预期结果: CYPRESS_baseUrl=https://someurl.com npx cypress-tags run -e TAGS='@limitedRun' GLOB='cypress/integration/**/*.feature' --headless --browser chrome

代码:

cmd = {}
with open("C:/Test/dev.ENV", mode="r", encoding="utf-8") as f:
  for line in f.readlines():
    splitted_line = line.split('=')
    k = splitted_line.pop(0).strip('\r\n\t')
    v = '='.join(splitted_line).strip('\r\n\t')
    cmd[k] = v

print('Command is ->')

final_cmd = f"{cmd['runCyCommand']} {cmd['tags']} {cmd['path']} {cmd['config']}"

# print command
print(final_cmd)

# import os library to be able set system variables and do system calls
import os

# set env CYPRESS_baseUrl for current shell
os.environ['CYPRESS_baseUrl'] = cmd['CYPRESS_baseUrl']

print('CYPRESS_baseUrl is set to ->')

# check if ENV set
if os.name == 'nt':
  # if OS is Windows, run Windows-specific command
  # not sure if this command will work. Can't check windows behaviour
  os.system('echo %CYPRESS_baseUrl%')
else:
  # this syntax for other POSIX shells (Linux, FreeBSD or MacOS)
  os.system('echo ${CYPRESS_baseUrl}')

# run npx command
print('Run NPX ->')
os.system(final_cmd)

输出:

Command is ->
npx cypress-tags run  -e TAGS='@limitedRun'  GLOB='tests/cypress/integration/**/*.feature'  --headless --browser chrome
CYPRESS_baseUrl is set to ->
https://someurl.com
Run NPX ->
npm ERR! could not determine executable to run
...

代码没有解释,很容易理解,但是如果你有问题,请问。