You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux下Python subprocess调用脚本报错:找不到python命令及目标脚本

问题详情

Windows下能正常运行的脚本,放到Linux上用subprocess调用同目录下的pythonfile.py时出错,两种调用方式及对应报错如下:

调用方式1

subprocess.run(['python','pythonfile.py',str(parsed_response)],shell = True)

报错信息:

pythonfile.py: 1: python: not found with shell

调用方式2

subprocess.call(['python', 'pythonfile.py',  str(parsed_response)])

报错信息:

Traceback (most recent call last):
  File "/home/user/.local/lib/python3.10/site-packages/telethon/client/updates.py", line 543, in _dispatch_update
    await callback(event)
  File "/home/user/Desktop/Tel_To_Disc_Bot/forwardgram.py", line 85, in handler
    subprocess.run(['python', 'pythonfile.py', parsed_response])
  File "/usr/lib/python3.10/subprocess.py", line 501, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.10/subprocess.py", line 969, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.10/subprocess.py", line 1845, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'python'
解决办法

1. 替换Python命令为python3

Linux多数系统默认仅将Python3注册为python3命令,没有python这个软链接,直接把调用里的python换成python3即可:

修改后的方式1:

subprocess.run(['python3','pythonfile.py',str(parsed_response)], shell=True)

修改后的方式2:

subprocess.call(['python3', 'pythonfile.py', str(parsed_response)])

2. 使用当前脚本的Python解释器(更稳妥)

为避免不同环境下Python命令不一致的问题,直接调用当前脚本正在使用的解释器路径,通过sys.executable获取:

先导入sys模块:

import sys

再修改调用代码:

# 对应方式1
subprocess.run([sys.executable, 'pythonfile.py', str(parsed_response)], shell=True)

# 对应方式2
subprocess.call([sys.executable, 'pythonfile.py', str(parsed_response)])

3. 给目标脚本添加可执行权限(可选)

如果仍有问题,先给pythonfile.py添加执行权限:

chmod +x pythonfile.py

然后在pythonfile.py的第一行添加shebang声明:

#!/usr/bin/env python3

之后就可以直接通过脚本名调用:

subprocess.run(['./pythonfile.py', str(parsed_response)], shell=True)

内容的提问来源于stack exchange,提问作者Crus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 17:02:41