【发布时间】:2013-08-11 20:25:35
【问题描述】:
import os
import subprocess
import sys
import re
## fname_ext=sys.argv[1]
fname_ext=r"C:\mine\.cs\test.cs"
exe=os.path.splitext(fname_ext)[0]+".exe" # Executable
fdir=os.path.split(fname_ext)[0]
fcontent=open(fname_ext).read()
p_using=re.compile("\s*using\s+((\w+[.]*)+)")
p_namespace=re.compile("\s*namespace\s+(\w+)")
usings=p_using.findall(fcontent)
usings=[x[0] for x in usings]
references=[]
for i in os.listdir(fdir):
path=fdir+"\\"+i
try:
if os.path.isdir(path) or (not path.endswith('cs')):continue
with open(path) as fp:
content=fp.read()
namespaces=p_namespace.findall(content)
for n in namespaces:
if n in usings and 'System' not in n:
references+=[path]
except:
pass
command="csc /nologo "+" ".join(references)+" "+fname_ext
## command=" ".join(references)
#~ ---------------------------------------------------------
# Build:
option=1
if option==0:
# using os.system
print ">>",command
if os.system(command)==0:
os.system(exe)
else:
#~ Using subprocess module
## print type(references)
command=['csc']
## print command,references
command.extend(["/nologo","/out:"+exe])
command.extend(references)
command.append(fname_ext)
## print command
if subprocess.call(command,shell=True)==0:
## print "running %s"%exe
subprocess.call([exe],shell=True)
else:
pass
## print "Failed to run"
#~ ---------------------------------------------------------
我上面有这段代码,它应该从SciTE 运行一个 Csharp 程序。它搜索
目录中的每个.cs 文件,并找到具有当前
文件已包含。在 SciTE 中运行文件的命令是:command.go.*.cs=python C:\mine\.py\csc.py $(FilePath)command.go.subsystem.*.cs=0
那个程序逻辑部分没问题。
问题是,当使用如下示例 Csharp 代码按 F5 时:
using System;
using System.Collections;
using MyNamespace;
class Test{
public static void Main(String[] args){
MyObject inst=new MyObject();
MyObject.self_destruct(inst);
}
}
运行正常。但是当我取消注释第二个 fname_ext 并评论第一个时
并运行 csc.py 文件,打开一个窗口并继续运行,打印 command(发生这种情况
使用os.system 选项)。当您使用 the subprocess.call 选项时,同样的事情
但这一次只有在shell=True 时才会发生。它只运行了 15 秒,就有 800+
cmd.exe 和 python.exe 进程。杀死 cmd.exe 后我不得不等待将近 5 分钟
让鼠标开始响应,再过 2 分钟让桌面窥视工作。
当shell=False 时,它运行正常,就像您从文件中按 F5 键时一样。
这里发生了什么?shell=True 在做什么这让它表现得那样吗?
【问题讨论】:
-
您能否记录足够的信息以查看每种情况下的
sys.argv是什么?因为显而易见的猜测是您正在运行自己的脚本,而不是您真正想要运行的东西。 -
实际上,Scite 是传递给 sys.argv($(FilePath)) 的那个。它传递字符串“C:\mine\.cs\test.cs”。我创建了第二个 fname_ext 以便在测试时可以在两者之间切换。当我运行 csc.py 和运行 test.cs 时,它输出相同的结果,所以我不认为我在运行自己的脚本。即使是同一个脚本,无论 shell 参数的值如何,结果都是相似的。
标签: python subprocess os.system scite