Python subprocess调用ltx命令报错:无法识别内部或外部命令
问题:通过Python subprocess调用Cygwin中的ltx程序失败
需求
通过Python的subprocess模块自动重复运行带-h参数的ltx程序,目标命令:ltx -h
当前环境与配置
- 已将ltx程序路径添加至Cygwin的
.bashrc,在Cygwin终端任意目录可直接执行ltx -h,配置内容:export PATH=$PATH:/home/joe/ltx/bin - 使用Cygwin64 Terminal,本地Python版本为3.12.2(Windows平台版本)
尝试操作与报错
初次调用测试
在Cygwin终端启动Python后执行:
import subprocess # 测试subprocess功能正常 subprocess.run(['ls','-al'],shell=True) # 运行成功 # 调用目标命令报错 subprocess.run(['ltx','-h'],shell=True)
报错信息:
'ltng-decoder' is not recognized as an internal or external command, operable program or batch file. CompletedProcess(args=['ltng-decoder', '-h'], returncode=1)
尝试绝对路径调用
subprocess.run([r"C:\cygwin64\joe\ltx\bin\ltx","-h"],shell=True)
报错信息:
'C:\cygwin64\home\joe\ltx\bin\ltx' is not recognized as an internal or external command, operable program or batch file. CompletedProcess(args=['C:\cygwin64\home\joe\ltx\bin\ltx', '-h'], returncode=1)
更新PATH后的测试
- 新增PATH配置:
export PATH=$PATH:/home/joe/mos export PATH="$PATH:C:\cygwin64\home\ephiiam\ltng\bin" - 确认PATH已包含
C:\cygwin64\home\joe\ltx\bin,直接运行ltx -h正常,但subprocess调用仍失败:
报错信息:import subprocess subprocess.run(['ltx','-h'], shell=True)'ltx' is not recognized as an internal or external command, operable program or batch file. CompletedProcess(args=['ltx', '-h'], returncode=1)
补充测试
在Cygwin终端手动追加PATH后:
export PATH="$PATH:C:\cygwin64\home\joe\ltx\bin" ltx -h # 运行正常,输出帮助信息
但Python中调用仍失败:
- 不使用
shell=True的情况:
报错:subprocess.run(['ltx','-h'])Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python\Python312\Lib\subprocess.py", line 548, in run with Popen(*popenargs, **kwargs) as process: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python\Python312\Lib\subprocess.py", line 1026, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "C:\Python\Python312\Lib\subprocess.py", line 1538, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: [WinError 2] The system cannot find the file specified - 使用
shell=True的情况:
报错:subprocess.run('ltx -h', shell=True)'ltx' is not recognized as an internal or external command, operable program or batch file. CompletedProcess(args='ltx -h', returncode=1)
请求解决
需要实现通过subprocess成功运行ltx -h,请提供解决方法或下一步尝试方向。
内容的提问来源于stack exchange,提问作者GershwinX
相关产品推荐
相关产品推荐

