gpt4 book ai didi

Python函数: using a batch file to pass parameters from . txt文件转python函数并执行函数

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:38 25 4
gpt4 key购买 nike

我想使用批处理文件将 1 个或多个参数从文本文件传递到 python 函数。这可能吗?理想情况下,我想从文本文件中的一行读取内容,该行会将特定的 com 端口传递给 python 函数 my_function ,并且这些操作可以使用批处理文件来完成

我目前可以使用批处理文件调用 python 脚本,如下所示。我还可以单独调用 python 函数并使用 Python Shell 向其传递参数。我需要能够将不同的值从文本文件传递到同一个函数,这就是我陷入困境的地方。

任何帮助将不胜感激。

调用Python脚本的当前批处理文件代码

echo[
@echo. The Step below calls the script which opens COM 12
echo[

"C:\Python\python.exe" "C:\Scripts\open_COM12.py"

当前用于传递参数(com 端口号)并调用 python 函数的 python 代码

import ConfigComPort as cw
from ConfigComPort import my_function
my_function('12')

连接成功

文本文件内容

COM_PORTS
12
19
23
22

最佳答案

如果您有一个名为 parameters.txt 的文件有数据

foo
bar
foobar

还有一个函数

def my_function(some_text):
print("I was called with " + some_text)

然后您可以这样做将文件的每一行传递给函数:

with open('parameters.txt', 'r') as my_file:
for line in my_file:
# remove the # and space from the next line to enable output to console:
# print(line.rstrip())

my_function(line.rstrip())

请注意 rstrip()我所有示例中的方法都会去掉尾随换行符(以及其他尾随空格),否则它们将成为每行的一部分。

如果您的参数文件有 header (如您的示例所示),您有多种可能性可以跳过该 header 。

例如,您可以一次将所有行读入列表,然后迭代子集:

with open('parameters.txt', 'r') as my_file:
all_lines = [line.rstrip() for line in my_file.readlines()]

# print(all_lines)

for line in all_lines[1:]:
# print(line)

my_function(line)

但是,这只会忽略 header 。如果您不小心传递了错误的文件或包含无效内容的文件,这可能会带来麻烦。

最好检查一下文件头是否正确。您只需扩展上面的代码即可:

with open('parameters.txt', 'r') as my_file:
all_lines = [line.rstrip() for line in my_file.readlines()]

# print(all_lines)

if all_lines[0] != 'COM_PORTS':
raise RuntimeError("file has wrong header")

for line in all_lines[1:]:
# print(line)

my_function(line)

或者您可以在循环内执行此操作,例如:

expect_header = True

with open('parameters.txt', 'r') as my_file:
for line in my_file:
stripped = line.rstrip()
if expect_header:
if stripped != 'COM_PORTS':
raise RuntimeError("header of file is wrong")

expect_header = False
continue

# print(stripped)

my_function(stripped)

或者您可以使用生成器表达式来检查循环外部的 header :

with open('parameters.txt', 'r') as my_file:
all_lines = (line.rstrip() for line in my_file.readlines())

if next(all_lines) != 'COM_PORTS':
raise RuntimeError("file has wrong header")

for line in all_lines:
# print(line)

my_function(line)

我可能更喜欢最后一个,因为它具有清晰的结构并且没有魔数(Magic Number)(例如 01 ,分别指哪一行是标题以及要跳过多少行)并且它不需要一次将所有行读入内存。

但是,如果您想对它们进行进一步处理,则将所有行一次读取到列表中的解决方案可能会更好,因为在这种情况下数据已经可用,并且您不需要再次读取文件.

关于Python函数: using a batch file to pass parameters from . txt文件转python函数并执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55629263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com