简体   繁体   English

将 argu.nets 从另一个 script.py 文件传递到一个 script.py 文件

[英]Passing argumnets to one script.py file from another script.py file

I want script1.py to loop a list and pass its output as an argument for another python file.我希望 script1.py 循环一个列表并将其 output 作为另一个 python 文件的参数传递。

script1.py脚本1.py

list = ['1','2','3']

for x in list:
    subprocess.call("python3 script2.py", shell=True)

I want script2.py to use x as its input我希望 script2.py 使用 x 作为输入

Let's say the script2.py file is a file such as:假设script2.py文件是这样的文件:

  • script2.py脚本2.py
import sys

argv = sys.argv
print(argv)

As you can see, this python file just shows the input argument.如您所见,这个 python 文件只显示了输入参数。 Note that the first argument always will be the file name.请注意,第一个参数始终是文件名。

Now suppose we want to loop over a list and pass the list elements to this script file as an argument.现在假设我们要遍历一个列表并将列表元素作为参数传递给这个脚本文件。 What we need to do simply is what follows:我们需要做的很简单,如下:

  • script1.py脚本1.py
import subprocess
myList = ["arg_1", "arg_2", "arg_3"]
for x in myList:
  result = subprocess.run(["python", 'script2.py', x], stdout=subprocess.PIPE)
  print(result.stdout.decode("UTF-8").strip())

Note that script1.py and script2.py are in the same folder(directory).请注意, script1.pyscript2.py位于同一文件夹(目录)中。

Output Output

['script2.py', 'arg_1']
['script2.py', 'arg_2']
['script2.py', 'arg_3']

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

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