【问题标题】:How to use one Python script to run another Python script and pass variables to it? [duplicate]如何使用一个 Python 脚本运行另一个 Python 脚本并将变量传递给它? [复制]
【发布时间】:2020-09-02 16:24:21
【问题描述】:

我有一个 Python 脚本。我们称之为 controller.py。我想使用 controller.py 来运行另一个 Python 脚本并将几个变量传递给它。我们将第二个脚本称为 analyzer.py

不将 analyzer.py 作为模块导入的最佳方法是什么?以及如何在该脚本中引用我传递给 analyzer.py 的变量?

这是我使用子进程失败的尝试:

controller.py

import subprocess

var1='mytxt'
var2=100
var3=True
var4=[['x','y','z'],['x','c','d']]
var5=r"C:\\Users\\me\\file.txt"

myargs=var1,var2,var3,var4,var5
my_lst_str = ' '.join(map(str, myargs))
my_lst_str ='python analyzer.py '+my_lst_str

subprocess.call(my_lst_str,shell=True)

analyzer.py

print 'Argument List:', str(sys.argv)

我在 Stack Overflow 上查看过类似的问题。我尝试过的一个经常推荐的解决方案是将analyzer.py 作为模块导入,但analyzer.py 定义了许多不同的功能。将其用作模块会创建许多嵌套函数,并且在这些嵌套函数中管理变量的范围很麻烦。

我需要为这些脚本使用 Python 2。我在 Windows 10 机器上。

【问题讨论】:

  • 我不太明白如何将analyzer.py 作为模块导入可以创建嵌套函数。嵌套函数是在另一个函数中定义的函数。也许值得在这里分享一些实际的代码。如果您坚持不导入analyzer.py,可以将其作为单独的python 进程运行subprocess
  • 导入模块是正常的,应该不会很麻烦。
  • @thgro 你说的是from analyzer import *吗?因为那将导入所有内容。如果您只想要模块中的单个功能,请仅导入该功能,例如from analyzer import the_function。尽可能少的全局变量(可能为零:常量是可以的,但最好将它们设为枚举)。如果函数需要变量,请将其作为参数传入。如果您继续传递相同的参数,请将它们分组为classnamedtuple
  • 关于您尝试使用subprocess:您不能只将列表列表转换为字符串,然后期望python 将其转换回来。你做事很艰难,但如果你坚持,看看ast.literal_eval

标签: python python-2.x


【解决方案1】:

1-exec 命令:

python2:

execfile('test.py')

python3:

exec(open('test.py').read())

2-os 命令:

test1.py:

import os 

#os.system('python test2.py')
os.system("python test2.py arg1 arg2")  

test2.py:

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

3- subprocess 命令:

from subprocess import call
call(["python", "test.py"])

传递参数和shell命令使用subprocess(请看Link):

import subprocess

# Simple command
subprocess.call(['ls', '-1'], shell=True)

另一个示例代码:

file1.py:

args ='python file2.py id ' + 1
subprocess.call(args)

file2.py:

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

4- socket pogramming:在两个或多个可以使用的 python 文件之间共享数据socket programming:见Link

【讨论】:

  • 谢谢塔赫。我在我的问题中添加了一些尝试使用子进程的代码。你能告诉我我的代码有什么问题吗?
  • import sys in analyzer.py 并删除 shell=True in subprocess.call(my_lst_str,shell=True) => subprocess.call(my_lst_str) 然后测试你的代码
猜你喜欢
  • 2015-09-14
  • 2014-02-24
  • 2019-10-22
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多