Python 如何执行纯 shell 脚本
查到的一些方法如 os.system(),os.popen(),os.exec() 等,都不是执行纯 shell 脚本啊,最简单的,我想通过 python 执行 shell,进入到某个文件夹中操作,该怎么操作?os.system("cd test sudo ./start.sh")没用啊
Python 如何执行纯 shell 脚本
在Python里直接跑纯shell脚本,最直接的办法就是用subprocess模块。这玩意儿就是专门用来搞系统命令和外部程序的。
最常用的就是subprocess.run(),它简单直接,能等命令跑完再继续。比如你有个脚本叫myscript.sh,可以这么干:
import subprocess
# 直接执行脚本文件
result = subprocess.run(['bash', 'myscript.sh'], capture_output=True, text=True)
# 检查返回码
if result.returncode == 0:
print("脚本执行成功!")
print("输出内容:", result.stdout)
else:
print("脚本执行失败!")
print("错误信息:", result.stderr)
参数说明:
['bash', 'myscript.sh']:第一个元素是shell解释器(比如bash),第二个是脚本路径。capture_output=True:捕获命令的标准输出和错误输出。text=True:让返回的stdout/stderr是字符串而不是字节。
如果你想直接执行一段shell命令字符串,可以加上shell=True参数:
import subprocess
# 执行shell命令字符串
cmd = "echo 'Hello from shell' && ls -la"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
print(result.stdout)
重要提醒: 用shell=True时要小心,特别是处理用户输入的时候,可能有安全风险(命令注入)。
如果你不需要等脚本跑完,或者想边跑边处理输出,可以用subprocess.Popen():
import subprocess
# 启动进程,不等待
proc = subprocess.Popen(['bash', 'myscript.sh'], stdout=subprocess.PIPE, text=True)
# 可以在这里干别的,或者逐行读取输出
for line in proc.stdout:
print("收到输出:", line.strip())
# 最后等待进程结束
proc.wait()
简单说,想省事就用subprocess.run(),要更灵活的控制就用subprocess.Popen()。
搜索“ python 切换目录”第一个搜索结果。。。os.chdir(’/Users/<username>/Desktop/’)
cd test; sudo ./start.sh
sudo 需要交互输入密码,你确定要用 sudo ?
cd 不是系统命令啊,少年.
os.system(“sudo bash -c ‘cd a; ./test.sh’”)
subprocess 了解一下
我执行的是 shell 不是系统命令
确定
直接用绝对路径不可以吗?
应该是 cd test; 或者 cd test\n ?
这种问题我已经不知道该建议你先多学下 shell 还是先多学下 python 了…
确定
shell 中有分号吗,没见过啊
要会的话,我就不来这里提问了
根据#11 来看,你先多学下 shell 吧
我第一次知道 shell 居然还有纯 shell 脚本一说
你要先进一个目录在执行脚本其实是两条命令,bash 多条命令需要用;分隔,你执行的是脚本需要用 bash 执行,用./的话需要在脚本第一行申明解析器,os.system 不接受标准输入,所以你的密码输不进去,可以 sudo 执行 python 脚本,这里就不需要用 sudo 了
cd test && sudo ./start.sh
pexpect,支持输入密码,等待加载等功能。subprocess.run()只支持一步操作,反正多个操作我没模拟成功
绝对路径就是了
&&
def run_sh(command, strict=True):
cmd = [b"bash"]
if strict:
cmd.append(b"-e")
return subprocess.run(cmd, input=command.encode(“utf-8”), stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=strict)
看上去很 6,学习一下
试试
import subprocess
subprocess.call("[ -d Pic ] && { rm -r Pic ; mkdir Pic; } || mkdir Pic", shell=True)
老铁,调不通啊,这个,是缩进不对吗?
TypeError: a bytes-like object is required, not 'str’
https://www.picb.cc/image/2bCbEa
#23 …
#23 …错误不已经报了么 类型不对。。。
shell 脚本就是 bash/zsh/xsh 来执行的
#!/usr/bin/perl6
# your code goes here
my \bash = Proc::Async.new: “/usr/bin/env”, “bash”, :w;
react {
–whenever bash.stdout.lines {
----.say;
–}
–whenever bash.start { }
–whenever IN.lines {
----bash.say(“s:g/^(\s+)/{ “–” x $0.codes }/; .say”);
----bash.close-stdin if s:g/^(\s+)/{ “–” x $0.codes }/; .say eq “exit”;
–}
}
try it online: https://ideone.com/wvp1ue
错了还不能改。。重新发一次 :(
#!/usr/bin/perl6
# your code goes here
my \bash = Proc::Async.new: “/usr/bin/env”, “bash”, :w;
react {
–whenever bash.stdout.lines {
----.say;
–}
–whenever bash.start { }
–whenever IN.lines {
----bash.say("$");
----bash.close-stdin if $ eq “exit”;
–}
}
怎么了老铁
哥,这水平劝你先学学英语,再学学 python,再来 v 站提问题吧。。。在这之前你的问题都可以问百度
os.popen(“cd /tmp/test;sudo ./start.sh”).read()
绝对路径和分号了解一下
你先得确定 os.system 用了啥 shell。不一定是 bash
无所谓,后面强制使用 bash 执行就可以了。
不好意思,哥不会英语

