查到的一些方法如 os.system(),os.popen(),os.exec()
等,都不是执行纯 shell 脚本啊,最简单的,我想通过 python 执行 shell,进入到某个文件夹中操作,该怎么操作?os.system("cd test sudo ./start.sh")
没用啊
为什么没有卵用????
os.system("[ -d Pic ] && { rm -r Pic ; mkdir Pic; } || mkdir Pic")
1 yyttll 2018-05-23 09:21:39 +08:00 ![]() |
2 ddrobot 2018-05-23 09:24:05 +08:00 搜索“ python 切换目录”第一个搜索结果。。。os.chdir('/Users/<username>/Desktop/') |
![]() | 5 nongmei 2018-05-23 09:39:20 +08:00 subprocess 了解一下 |
![]() | 8 xia0chun 2018-05-23 10:04:08 +08:00 直接用绝对路径不可以吗? |
9 walleL 2018-05-23 10:08:07 +08:00 应该是 cd test; 或者 cd test\n ? |
![]() | 10 xiaket 2018-05-23 10:10:45 +08:00 ![]() 这种问题我已经不知道该建议你先多学下 shell 还是先多学下 python 了... |
![]() | 14 shuizhengqi 2018-05-23 10:18:00 +08:00 我第一次知道 shell 居然还有纯 shell 脚本一说 |
15 lieh222 2018-05-23 10:19:44 +08:00 @wsds 你要先进一个目录在执行脚本其实是两条命令,bash 多条命令需要用;分隔,你执行的是脚本需要用 bash 执行,用./的话需要在脚本第一行申明解析器,os.system 不接受标准输入,所以你的密码输不进去,可以 sudo 执行 python 脚本,这里就不需要用 sudo 了 |
17 princelai 2018-05-23 10:39:38 +08:00 pexpect,支持输入密码,等待加载等功能。subprocess.run()只支持一步操作,反正多个操作我没模拟成功 |
![]() | 18 ClutchBear 2018-05-23 10:49:57 +08:00 绝对路径就是了 |
![]() | 19 cctv6 2018-05-23 10:52:10 +08:00 via iPhone && |
![]() | 20 virusdefender 2018-05-23 11:15:08 +08:00 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) |
21 wsds OP @virusdefender 看上去很 6,学习一下 |
![]() | 22 Qzier 2018-05-23 12:02:29 +08:00 试试 import subprocess subprocess.call("[ -d Pic ] && { rm -r Pic ; mkdir Pic; } || mkdir Pic", shell=True) |
23 wsds OP @virusdefender 老铁,调不通啊,这个,是缩进不对吗? TypeError: a bytes-like object is required, not 'str' https://www.picb.cc/image/2bCbEa |
![]() | 24 extreme 2018-05-23 12:55:25 +08:00 |
![]() | 25 virusdefender 2018-05-23 12:57:20 +08:00 @wsds #23 ... |
![]() | 27 araraloren 2018-05-23 16:58:19 +08:00 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 |
![]() | 28 araraloren 2018-05-23 17:00:58 +08:00 错了还不能改。。重新发一次 :( #!/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"; --} } |
29 wsds OP @virusdefender 怎么了老铁 |
30 alvin666 2018-05-23 19:30:26 +08:00 via Android @wsds 哥,这水平劝你先学学英语,再学学 python,再来 v 站提问题吧。。。在这之前你的问题都可以问百度 |
![]() | 32 ipwx 2018-05-23 19:56:51 +08:00 你先得确定 os.system 用了啥 shell。不一定是 bash |