从另一个 Python 脚本运行 Python 脚本,传入参数 [英] Run a Python script from another Python script, passing in arguments

查看:37
本文介绍了从另一个 Python 脚本运行 Python 脚本,传入参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从另一个 Python 脚本运行一个 Python 脚本.我想像使用命令行一样传递变量.

I want to run a Python script from another Python script. I want to pass variables like I would using the command line.

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

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.

我找到了 Stack Overflow question 1186789 这是一个类似的问题,但 ars 的答案调用了一个函数,因为我想运行整个脚本,而不仅仅是一个函数,而 balpha 的答案调用脚本但没有参数.我将其更改为如下所示的内容作为测试:

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. I changed this to something like the below as a test:

execfile("script2.py 1")

但它没有正确接受变量.当我打印出 script2.py 中的 sys.argv 时,它是对第一个脚本['C:\script1.py'] 的原始命令调用.

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),因为我不拥有它.

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

我想一定有办法做到这一点;我只是很困惑你是怎么做到的.

I figure there must be a way to do this; I am just confused how you do it.

推荐答案

尝试使用 os.系统:

os.system("script2.py 1")

execfile 不同,因为它旨在在当前 执行上下文中运行一系列 Python 语句.这就是 sys.argv 没有为您改变的原因.

execfile is different because it is designed to run a sequence of Python statements in the current execution context. That's why sys.argv didn't change for you.

这篇关于从另一个 Python 脚本运行 Python 脚本,传入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆