3

i'm trying to get simple python script to call another script, just in order to understand better how it's working. The 'main' code goes like this:

#!/usr/bin/python
import subprocess
subprocess.call('kvadrat.py')

and the script it calls - kvadrat.py:

#!/usr/bin/python
def kvadriranje(x):
    kvadrat = x * x
    return kvadrat

print kvadriranje(5)

Called script works on its own, but when called through 'main' script error occurs:

Traceback (most recent call last):
  File "/Users/user/Desktop/Python/General Test.py", line 5, in <module>
    subprocess.call('kvadrat.py')
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 595, in __init__
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 1106, in _execute_child
OSError: [Errno 2] No such file or directory

Obviously something's wrong, but being a beginner don't see what.

4

3 回答 3

3

您需要为其提供您尝试调用的脚本的完整路径,如果您想动态执行此操作(并且您在同一目录中),您可以执行以下操作:

import os    
full_path = os.path.abspath('kvadrat.py')
于 2013-07-30T15:14:53.003 回答
3

你有没有尝试过:

from subprocess import call
call(["python","kvadrat.py"]) #if in same directory, else get abs path

您还应该检查您的文件是否存在:

import os
print os.path.exists('kvadrat.py')
于 2013-07-30T15:47:30.303 回答
0

Subprocess.call 要求文件是可执行的并且在路径中找到。在 unix 系统中,可以尝试使用subprocess.call(['./kvadrat.py'])在当前工作目录下执行一个 kvadrat.py 文件,并确保其kvadrat.py具有可执行权限;或者您可以将它复制到 PATH 中的一个目录,例如 /usr/local/bin - 然后它可以从任何地方执行。

大多数时候,您不想使用子进程运行其他 python 应用程序,而只是将它们作为模块导入,但是......

于 2013-07-30T15:16:55.900 回答