简体   繁体   English

Python:通过参数传递在另一个 python 脚本中循环 python 脚本

[英]Python: looping a python script in another python script with parameter passing

I am trying to run a py script in loop from another py file with a parameter passing.我正在尝试通过传递参数从另一个 py 文件循环运行 py 脚本。

I am trying the following:我正在尝试以下操作:

Script1: 
lst = [12,23,45,67,89]
age_lst = []
for i in lst:
  age_i = os.system("python script_to_run {0}".format(int(i)) )
  age_lst.append(age_i)

Below is the code for script_to_run.py下面是script_to_run.py的代码

Script2:script_to_run.py
def age(age:int):
  estimated_val = age+2
  return estimated_val
if __name__=="__main__":
  my_age = int(sys.argv[1])
  final_age = age(age=my_age)
  print(final_age)

Whenever I am running Script 1 where I am calling Script 2 (script_to_run.py) It is running fine but age_lst[] is being populated only with 2.每当我在调用脚本 2 (script_to_run.py) 的地方运行脚本 1 时,它运行良好,但age_lst[]仅填充了 2。

Expectation is期望是

age_lst = [14,25,47,69,91] <---adding 2 with all elements in age_lst

What I am missing?我错过了什么?

Also when I am running the Script1.py from cmd, I am getting error python: can't open file 'script_to_run': [Errno 2] No such file or directory另外,当我从 cmd 运行Script1.py时,我收到错误python: can't open file 'script_to_run': [Errno 2] No such file or directory

I am using Windows 10.我正在使用 Windows 10。

os.system runs the program and returns its exit code. os.system运行程序并返回其退出代码。 Your script writes to standard output, a different beast entirely.您的脚本写入标准 output,完全不同的野兽。 Exactly what returns from os.system is OS dependent.os.system返回的确切内容取决于操作系统。 On linux for example, its the exit code, limited to 0-255, shifted left with signal information added.例如,在 linux 上,其exit代码限制为 0-255,向左移动并添加了信号信息。 Messy.凌乱。

But since you are converting the output to a string and printing to stdout anyway, just have the parent process read that.但是,由于您要将 output 转换为字符串并打印到标准输出,因此只需让父进程读取它即可。 The subprocess module has several functions that run programs. subprocess模块有几个运行程序的函数。 run is the modern way. run是现代的方式。

import subprocess as subp
import sys

lst = [12,23,45,67,89]
age_lst = []
for i in lst:
    proc = subp.run([sys.executable, "script_to_run.py", str(i)],
        stdout=subp.PIPE)
    if proc.returncode == 0:
        print("script returned error")
    else:
        age_lst.append(int(proc.stdout))
print(age_lst)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM