如何将bash脚本导出到python?

2024-05-14 07:10:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python导出以下代码:

#!/usr/bin/env bash

export LANG="en_US.UTF-8" LC_ALL="en_US.UTF-8"

echo Starting carddav sync at $(date)

mkdir -p carddav

cat vdirsyncer.config.template | sed 
"s/VDIRSYNC_USER/$VDIRSYNC_USER/; s/VDIRSYNC_PASS/$VDIRSYNC_PASS/" > 
vdirsyncer.config

yes | vdirsyncer -c vdirsyncer.config discover

vdirsyncer -c vdirsyncer.config sync

rm vdirsyncer.config

echo Carddav sync done, starting carddavsync

我试图利用bash2py,但没有成功。你知道吗


Tags: 代码echoenvconfigbinusrpasssync
3条回答

最简单的方法是使用所需内容创建bash脚本,然后在python中执行它。 一定要给它execution Permissions,如果它不在同一个目录中,则可能将Path更改为脚本。你知道吗

#!/usr/bin/python

import subprocess
subprocess.call("./mybashscript.sh", shell=True)

尝试导入os库,然后将bash指令传递给函数system,例如:

import os
bashCommand = 'export LANG="en_US.UTF-8" LC_ALL="en_US.UTF-8'
os.system(bashCommand)

可以使用子进程在python代码中执行bash/shell脚本。举个例子:

import subprocess

command = "npm-cli-login -u "+user+" -p \""+password+"\" -e "+email+" -r \""+self.nexusUrl+"/repository/deploy.npm.cloud/\"  config-path npmrc"

process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
output, error = process.communicate()

你可以在这里阅读更多:https://docs.python.org/3/library/subprocess.html

相关问题 更多 >

    热门问题