【问题标题】:Subprocess in Python: File Name too longPython中的子进程:文件名太长
【发布时间】:2015-04-20 11:50:50
【问题描述】:

我尝试通过 Python 2.6 中的 subprocess 模块调用 shellscript。

import subprocess

shellFile = open("linksNetCdf.txt", "r")

for row in shellFile:
    subprocess.call([str(row)])

我的文件名长度在 400 到 430 个字符之间。 调用脚本时出现错误:

File "/usr/lib64/python2.6/subprocess.py", line 444, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib64/python2.6/subprocess.py", line 595, in __init__
errread, errwrite)
File "/usr/lib64/python2.6/subprocess.py", line 1106, in _execute_child
raise child_exception
OSError: [Errno 36] File name too long

linksNetCdf.txt 中的行示例是

./ShellScript 'Title' 'Sometehing else' 'InfoInfo' 'MoreInformation' inputfiile outputfile.txt 3 2

任何想法如何仍然运行脚本?

【问题讨论】:

  • 你有没有试过弄清楚你的系统上文件名的最大允许长度是多少getconf NAME_MAX /
  • 可能会显示 head 的 linksNetCdf.txt
  • @flazzarini 当我“手动”键入它或从 .txt 复制链接时它可以工作。并将其粘贴到 ssh 安全客户端中...
  • @JoseRicardoBustosM。不,.txt 中没有头,只有 ./..sh ... 命令
  • @Stoffer: 不,他的意思是运行命令head linksNetCdf.txt,然后向我们展示结果...

标签: python shell


【解决方案1】:

subprocess.call 可以通过两种方式运行命令 - 可以是您在 shell 中键入的单个字符串,也可以是可执行文件名称列表和参数。

你想要第一个,但正在使用第二个

import subprocess

shellFile = open("linksNetCdf.txt", "r")

for row in shellFile:
    subprocess.call(row, shell=True)

通过将您的row 转换为包含单个字符串的列表,您的意思是“运行名为echo these were supposed to be arguments 的命令,不带参数”

【讨论】:

  • 我要运行的命令中有参数。 Jose Ricardo Bustos M. 提到这可能有问题。
  • 这支持有参数就好了。您可以尝试使用subprocess.call(row, shell=True)
【解决方案2】:

您需要告诉子进程将该行作为包含参数的完整命令执行,而不仅仅是一个程序。

这是通过传递 shell=True 来调用来完成的

 import subprocess
 cmd = "ls " + "/tmp/ " * 30
 subprocess.call(cmd, shell=True)

【讨论】:

    猜你喜欢
    • 2013-05-07
    • 2021-08-14
    • 2021-12-14
    • 1970-01-01
    • 2014-05-30
    • 2015-04-18
    • 2019-08-19
    • 2017-03-06
    相关资源
    最近更新 更多