Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

python - 从另一个Python脚本运行一个Python脚本,并传入参数[重复](Run a Python script from another Python script, passing in arguments [duplicate])

This question already has an answer here:

(这个问题已经在这里有了答案:)

I want to run a Python script from another Python script.

(我想从另一个Python脚本运行一个Python脚本。)

I want to pass variables like I would using the command line.

(我想像使用命令行一样传递变量。)

For example, I would run my first script that would iterate through a list of values (0,1,2,3) and pass those to the 2nd script script2.py 0 then script2.py 1 , etc.

(例如,我将运行我的第一个脚本,该脚本将遍历值列表(0,1,2,3)并将其传递给第二个脚本script2.py 0然后script2.py 1等。)

I found Stack Overflow question 1186789 which is a similar question, but ars's answer calls a function, where as I want to run the whole script, not just a function, and balpha's answer calls the script but with no arguments.

(我发现了Stack Overflow问题1186789 ,这是一个类似的问题,但是ars的答案调用了一个函数,在这里我想运行整个脚本,而不仅仅是函数,而balpha的答案则调用了脚本,但没有参数。)

I changed this to something like the below as a test:

(我将其更改为以下内容作为测试:)

execfile("script2.py 1")

But it is not accepting variables properly.

(但是它没有正确接受变量。)

When I print out the sys.argv in script2.py it is the original command call to first script "['C:\script1.py'].

(当我在script2.py中打印sys.argv ,它是对第一个脚本“ ['C:\ script1.py']的原始命令调用。)

I don't really want to change the original script (ie script2.py in my example) since I don't own it.

(我真的不想更改原始脚本(例如,在我的示例中为script2.py),因为我不拥有它。)

I figure there must be a way to do this;

(我认为必须有一种方法可以做到这一点;)

I am just confused how you do it.

(我只是很困惑你怎么做。)

  ask by Gern Blanston translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try using os.system :

(尝试使用os.system :)

os.system("script2.py 1")

execfile is different because it is designed to run a sequence of Python statements in the current execution context.

(execfile有所不同,因为它旨在在当前执行上下文中运行一系列Python语句。)

That's why sys.argv didn't change for you.

(这就是sys.argv不会为您更改的原因。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...