[英]How to use one Python script to run another Python script and pass variables to it?
I have one Python script.我有一个 Python 脚本。 Let's call it controller.py .
我们称之为controller.py 。 I'd like to use controller.py to run another Python script and pass several variables to it.
我想使用controller.py运行另一个 Python 脚本并将几个变量传递给它。 Let's call the second script analyzer.py .
让我们调用第二个脚本analyzer.py 。
What is the best way to do this without importing analyzer.py as module?如果不将analyzer.py作为模块导入,最好的方法是什么? And how do I reference the variables I'm passing to analyzer.py within that script?
以及如何在该脚本中引用我传递给analyzer.py的变量?
Here's my failed attempt using subprocess:这是我使用子进程失败的尝试:
controller.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分析器.py
print 'Argument List:', str(sys.argv)
I have looked through similar questions on Stack Overflow.我在 Stack Overflow 上查看了类似的问题。 One oft-recommended solution I tried was importing analyzer.py as a module, but analyzer.py defines many different functions.
我尝试过的一个经常推荐的解决方案是将analyzer.py 作为模块导入,但analyzer.py 定义了许多不同的功能。 Using it as a module creates lots of nested functions, and managing the scope of variables within those nested functions was cumbersome.
将其用作模块会创建许多嵌套函数,并且在这些嵌套函数中管理 scope 变量非常麻烦。
I need to use Python 2 for these scripts.我需要为这些脚本使用 Python 2 。 I'm on a Windows 10 machine.
我在 Windows 10 机器上。
1- exec
command: 1-
exec
命令:
python2:蟒蛇2:
execfile('test.py')
python3:蟒蛇3:
exec(open('test.py').read())
2- os
command: 2-
os
命令:
test1.py:测试1.py:
import os
#os.system('python test2.py')
os.system("python test2.py arg1 arg2")
test2.py:测试2.py:
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
3- subprocess
command: 3-
subprocess
命令:
from subprocess import call
call(["python", "test.py"])
for passing argument and shell command use subprocess
(plz see this Link ):用于传递参数和 shell 命令使用
subprocess
进程(请参阅此链接):
import subprocess
# Simple command
subprocess.call(['ls', '-1'], shell=True)
another example code:另一个示例代码:
file1.py:文件 1.py:
args ='python file2.py id ' + 1
subprocess.call(args)
file2.py:文件2.py:
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
4- socket pogramming
: share data between two or many python file you can use socket programming
: see this Link . 4
socket pogramming
:在两个或多个python文件之间共享数据你可以使用socket programming
:见这个链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.