简体   繁体   English

将python变量传递给另一个脚本

[英]Passing python variable to another script

I am pretty new to programming with python. 我对使用python编程非常陌生。 So apologies in advance: I have two python scripts which should share variables. 提前道歉:我有两个应该共享变量的python脚本。 Furthermore the first script (first.py) should call second script (second.py) 此外,第一个脚本(first.py)应该调用第二个脚本(second.py)

first.py: first.py:

import commands
x=5
print x
cmd = "path-to-second/second.py"
ou = commands.getoutput(cmd)
print x

second.py looks like this second.py看起来像这样

print x
x=10
print x

I would expect the output: 5 5 10 10 我期望输出:5 5 10 10

In principle I need a way to communicate between the two scripts. 原则上,我需要一种在两个脚本之间进行通信的方法。 Any solution which does this job is perfectly fine. 任何可以完成这项工作的解决方案都可以。

Thank you for your help! 谢谢您的帮助!

Tim 蒂姆

Each python script has its own root scope, and in this case you're launching another entirely separate process, so its x is completely different from the other script's x , otherwise each python script would have to have unique variable names to avoid collision. 每个python脚本都有其自己的根范围,在这种情况下,您将启动另一个完全独立的进程,因此它的x与另一个脚本的x完全不同,否则每个python脚本必须具有唯一的变量名,以避免冲突。

What you probably want to do is provide the values needed by second.py on the command line. 您可能想要做的是在命令行上提供second.py所需的值。 Here's a simple way to do that: 这是一种简单的方法:

first.py: first.py:

import commands
x=5
print x
cmd = "path-to-second/second.py " + str(x)
ou = commands.getoutput(cmd)

second.py: second.py:

import sys
x = int(sys.argv[1]) # sys.argv[0] is "second.py"
print x
x=10
print x

In your second.py, you'll want these lines 在您的second.py中,您需要这些行

from sys import argv
x = argv[1]   #Second argument (starts at 0, which is the script name)

Then your first.py should execute second.py such as 然后您的first.py应该执行second.py如

import os
os.system("python second.py " + x)

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

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