使用 Python 子进程调用来调用 Python 脚本 [英] Using a Python subprocess call to invoke a Python script

查看:42
本文介绍了使用 Python 子进程调用来调用 Python 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Python 脚本,需要调用同一目录中的另一个 Python 脚本.我是这样做的:

I have a Python script that needs to invoke another Python script in the same directory. I did this:

from subprocess import call
call('somescript.py')

我收到以下错误:

call('somescript.py')
File "/usr/lib/python2.6/subprocess.py", line 480, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.6/subprocess.py", line 633, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child

raise child_exception
OSError: [Errno 2] No such file or directory

虽然我在同一个文件夹中有脚本 somescript.py .我在这里遗漏了什么吗?

I have the script somescript.py in the same folder though. Am I missing something here?

推荐答案

如果 'somescript.py' 不是你通常可以直接从命令行执行的东西(即,$: somescript.py 工作),那么你不能直接使用 call 调用它.

If 'somescript.py' isn't something you could normally execute directly from the command line (I.e., $: somescript.py works), then you can't call it directly using call.

请记住,Popen 的工作方式是第一个参数是它执行的程序,其余的是传递给该程序的参数.在这种情况下,程序实际上是python,而不是您的脚本.因此,以下内容将按您的预期工作:

Remember that the way Popen works is that the first argument is the program that it executes, and the rest are the arguments passed to that program. In this case, the program is actually python, not your script. So the following will work as you expect:

subprocess.call(['python', 'somescript.py', somescript_arg1, somescript_val1,...]).

这会正确调用 Python 解释器并告诉它使用给定的参数执行您的脚本.

This correctly calls the Python interpreter and tells it to execute your script with the given arguments.

请注意,这与上述建议不同:

Note that this is different from the above suggestion:

subprocess.call(['python somescript.py'])

这将尝试执行名为 python somscript.py 的程序,该程序显然不存在.

That will try to execute the program called python somscript.py, which clearly doesn't exist.

call('python somescript.py', shell=True)

也可以使用,但使用字符串作为调用的输入不是跨平台的,如果您不是构建字符串的人,则很危险,通常应尽可能避免使用.

Will also work, but using strings as input to call is not cross platform, is dangerous if you aren't the one building the string, and should generally be avoided if at all possible.

这篇关于使用 Python 子进程调用来调用 Python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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